package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.service.condition.CustomerConditionServiceImpl;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.call.AliyunCall;
import com.xbongbong.paas.call.CallCenterService;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasListGroupEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.pojo.dto.SearchDataInConditionDTO;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.OtherExpenseSheetTypeEnum;
import com.xbongbong.paas.enums.OtherIncomeSheetTypeEnum;
import com.xbongbong.paas.enums.PaySheetTypeEnum;
import com.xbongbong.paas.enums.PaymentSheetTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.SheetTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.LinkDetailPojo;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.paas.field.LinkedAttrPoJo;
import com.xbongbong.paas.field.MultiUnitItemPoJo;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.field.UnitItemPoJo;
import com.xbongbong.paas.field.VisibleRulePoJo;
import com.xbongbong.paas.help.FormDataListSearchHelp;
import com.xbongbong.paas.help.FormDataValidateProductHelp;
import com.xbongbong.parent.help.ListGroupHelp;
import com.xbongbong.parent.help.PublicGroupHelp;
import com.xbongbong.paas.help.UserHelp;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasListGroupModel;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.DetaPhonePojo;
import com.xbongbong.parent.pojo.GroupConditionPoJo;
import com.xbongbong.paas.pojo.ProductFieldPojo;
import com.xbongbong.paas.pojo.ShareConditionFormatPojo;
import com.xbongbong.paas.pojo.dto.AggSumDTO;
import com.xbongbong.paas.pojo.dto.ExplainScreenListDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.FormDataSummaryDTO;
import com.xbongbong.paas.pojo.dto.ParseSingleRowDataDTO;
import com.xbongbong.paas.pojo.dto.UserAndDepartmentGetDTO;
import com.xbongbong.paas.pojo.vo.AggSumVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.pojo.vo.PrePayBalanceListVO;
import com.xbongbong.paas.pojo.vo.PrePaymentBalanceListVO;
import com.xbongbong.paas.pojo.vo.UserAndDepartmentGetVO;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.service.CallCenterCommonService;
import com.xbongbong.paas.service.PaasFormService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.DepartmentVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.parent.interfaces.BusinessConditionService;
import com.xbongbong.parent.pojo.list.ConditionListPojo;
import com.xbongbong.pro.businessdata.pojo.dto.ProductListDataDTO;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.constant.RangeScreenConstant;
import com.xbongbong.pro.domain.entity.ScoreRangeConditionEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.ReceiveStatusEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.TemplateErrorCodeEnum;
import com.xbongbong.pro.enums.fund.enums.ModelTypeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.formexplain.pojo.HandleExplainPojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.message.model.PushModel;
import com.xbongbong.pro.payment.pojo.vo.RelationshipGetPojo;
import com.xbongbong.pro.product.pojo.dto.FilterAttrOnOffJXCDTO;
import com.xbongbong.pro.product.pojo.vo.RelativeProductExplainVO;
import com.xbongbong.pro.score.pojo.dto.ScoreRangeDetailDTO;
import com.xbongbong.pro.score.pojo.vo.ScoreRangeDetailVO;
import com.xbongbong.pro.statistic.result.pojo.ElasticAggsPojo;
import com.xbongbong.pro.weblist.pojo.ListOptionPackagePojo;
import com.xbongbong.pro.weblist.pojo.TagPojo;
import com.xbongbong.pro.weblist.pojo.WaitContractPojo;
import com.xbongbong.pro.weblist.pojo.WaitContractProductPojo;
import com.xbongbong.pro.weblist.pojo.WaitOutstockProductPojo;
import com.xbongbong.pro.weblist.pojo.WaitPurchasePojo;
import com.xbongbong.pro.weblist.pojo.WaitPurchaseProductPojo;
import com.xbongbong.pro.workorder.pojo.TimeConsumingOutPojo;
import com.xbongbong.pro.workorder.pojo.vo.PaymentSheetDateEsListVO;
import com.xbongbong.pro.workorder.pojo.vo.WorkOrderDataEsListVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.PageConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.SaasConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.ContractDao;
import com.xbongbong.saas.domain.entity.AssembleProductEntity;
import com.xbongbong.saas.domain.entity.BomProductEntity;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.ContractUserEntity;
import com.xbongbong.saas.domain.entity.CostAdjustProductEntity;
import com.xbongbong.saas.domain.entity.CustomerFocusEntity;
import com.xbongbong.saas.domain.entity.CustomerStatementProductEntity;
import com.xbongbong.saas.domain.entity.InstockProductEntity;
import com.xbongbong.saas.domain.entity.InventoryProductEntity;
import com.xbongbong.saas.domain.entity.InvoiceRelationshipEntity;
import com.xbongbong.saas.domain.entity.OpportunityFocusEntity;
import com.xbongbong.saas.domain.entity.OpportunityProductEntity;
import com.xbongbong.saas.domain.entity.OutstockProductEntity;
import com.xbongbong.saas.domain.entity.PayBalanceEntity;
import com.xbongbong.saas.domain.entity.PaymentBalanceEntity;
import com.xbongbong.saas.domain.entity.ProductBaseInfoEntity;
import com.xbongbong.saas.domain.entity.ProductWarehouseEntity;
import com.xbongbong.saas.domain.entity.ProductionOrderProductEntity;
import com.xbongbong.saas.domain.entity.PromotionProductEntity;
import com.xbongbong.saas.domain.entity.PurchaseBalanceEntity;
import com.xbongbong.saas.domain.entity.PurchaseInvoiceRelationshipEntity;
import com.xbongbong.saas.domain.entity.PurchaseProductEntity;
import com.xbongbong.saas.domain.entity.QuotationProductEntity;
import com.xbongbong.saas.domain.entity.ReturnedPurchaseProductEntity;
import com.xbongbong.saas.domain.entity.SmartReplenishmentEntity;
import com.xbongbong.saas.domain.entity.SpecificationEntity;
import com.xbongbong.saas.domain.entity.SupplierProductEntity;
import com.xbongbong.saas.domain.entity.TransferProductEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFlowNodeEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.domain.entity.WorkOrderProductEntity;
import com.xbongbong.saas.domain.entity.WorkOrderStageEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateEntity;
import com.xbongbong.saas.domain.entity.ext.ContactEntityExt;
import com.xbongbong.saas.domain.entity.ext.ContractEntityExt;
import com.xbongbong.saas.domain.entity.ext.InvoiceEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentSheetEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.WarehouseEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderEntityExt;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.ContractProduceEnum;
import com.xbongbong.saas.enums.CreditLimitStatusEnum;
import com.xbongbong.saas.enums.CreditTemporaryApplyStatusEnum;
import com.xbongbong.saas.enums.CustomerStatementEnum;
import com.xbongbong.saas.enums.CustomerStatementProductEnum;
import com.xbongbong.saas.enums.CustomerStatementStatisticDistributorEnum;
import com.xbongbong.saas.enums.CustomerStatementStatisticEnum;
import com.xbongbong.saas.enums.CustomerStatementStatusEnum;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.ListBusinessTypeEnum;
import com.xbongbong.saas.enums.ListGroupEnum;
import com.xbongbong.saas.enums.ListOptionEnum;
import com.xbongbong.saas.enums.ListOptionTabEnum;
import com.xbongbong.saas.enums.OnlyInsertDBEnum;
import com.xbongbong.saas.enums.OperatePageEnum;
import com.xbongbong.saas.enums.OptionTableHeadEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.PaymentSourceTypeEnum;
import com.xbongbong.saas.enums.ReturnedPurchaseStatusEnum;
import com.xbongbong.saas.enums.SaasSpecialListEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.SheetAloneEnum;
import com.xbongbong.saas.enums.SubOptionTableHeadEnum;
import com.xbongbong.saas.enums.TagEnum;
import com.xbongbong.saas.enums.VisibleRangeEnum;
import com.xbongbong.saas.enums.WorkOrderNodeStatusEnum;
import com.xbongbong.saas.enums.WorkOrderTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.AssembleEnum;
import com.xbongbong.saas.enums.business.BomBillEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CompetitorEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CostAdjustEnum;
import com.xbongbong.saas.enums.business.CreditLimitEnum;
import com.xbongbong.saas.enums.business.CreditTemporaryLimitEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.DistributorAccountEnum;
import com.xbongbong.saas.enums.business.DistributorEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.InventoryEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.KnowledgeDataEnum;
import com.xbongbong.saas.enums.business.MarketingBaseEnum;
import com.xbongbong.saas.enums.business.OrderEnum;
import com.xbongbong.saas.enums.business.OtherExpenseEnum;
import com.xbongbong.saas.enums.business.OtherIncomeEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.enums.business.PromotionActivityManagementEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.PurchaseInvoiceEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.RefTypeEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.business.TransferEnum;
import com.xbongbong.saas.enums.business.WaitInstockEnum;
import com.xbongbong.saas.enums.business.WaitOutStockStatusEnum;
import com.xbongbong.saas.enums.business.WaitOutstockEnum;
import com.xbongbong.saas.enums.business.WaitPurchaseProductEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.dictionary.AllInBoundEnum;
import com.xbongbong.saas.enums.dictionary.AllOutBoundEnum;
import com.xbongbong.saas.enums.dictionary.ArchivedEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.enums.dictionary.DistributorAccountStatusEnum;
import com.xbongbong.saas.enums.dictionary.MarketingStatusEnum;
import com.xbongbong.saas.enums.dictionary.OrderStatusEnum;
import com.xbongbong.saas.enums.dictionary.PayPlanStatusEnum;
import com.xbongbong.saas.enums.dictionary.PaymentStatusEnum;
import com.xbongbong.saas.enums.dictionary.ShipStatusEnum;
import com.xbongbong.saas.enums.product.ContractProductEnum;
import com.xbongbong.saas.enums.product.CostAdjustProductEnum;
import com.xbongbong.saas.enums.product.ProductionOrderMaterielProductEnum;
import com.xbongbong.saas.enums.subform.ContractProductSubFormEnum;
import com.xbongbong.saas.model.AssembleProductModel;
import com.xbongbong.saas.model.BomProductModel;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.ContractUserModel;
import com.xbongbong.saas.model.CostAdjustProductModel;
import com.xbongbong.saas.model.CustomerFocusModel;
import com.xbongbong.saas.model.CustomerStatementProductModel;
import com.xbongbong.saas.model.DataDictionaryModel;
import com.xbongbong.saas.model.InstockModel;
import com.xbongbong.saas.model.InstockProductModel;
import com.xbongbong.saas.model.InventoryProductModel;
import com.xbongbong.saas.model.InvoiceModel;
import com.xbongbong.saas.model.InvoiceRelationshipModel;
import com.xbongbong.saas.model.OpportunityFocusModel;
import com.xbongbong.saas.model.OpportunityProductModel;
import com.xbongbong.saas.model.OutstockProductModel;
import com.xbongbong.saas.model.PaymentModel;
import com.xbongbong.saas.model.PaymentSheetModel;
import com.xbongbong.saas.model.ProductBaseInfoModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductionOrderProductModel;
import com.xbongbong.saas.model.PromotionProductModel;
import com.xbongbong.saas.model.PurchaseBalanceModel;
import com.xbongbong.saas.model.PurchaseInvoiceRelationshipModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.PurchaseProductModel;
import com.xbongbong.saas.model.QuotationProductModel;
import com.xbongbong.saas.model.ReturnedPurchaseProductModel;
import com.xbongbong.saas.model.ScoreRangeModel;
import com.xbongbong.saas.model.SmartReplenishmentModel;
import com.xbongbong.saas.model.SpecificationModel;
import com.xbongbong.saas.model.SupplierProductModel;
import com.xbongbong.saas.model.TagLinkModel;
import com.xbongbong.saas.model.TransferProductModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.saas.model.WorkOrderFlowNodeModel;
import com.xbongbong.saas.model.WorkOrderProductModel;
import com.xbongbong.saas.model.WorkOrderTemplateModel;
import com.xbongbong.saas.service.AssembleService;
import com.xbongbong.saas.service.BomBillService;
import com.xbongbong.saas.service.ContractProductService;
import com.xbongbong.saas.service.ContractService;
import com.xbongbong.saas.service.CreditLimitService;
import com.xbongbong.saas.service.FundSetService;
import com.xbongbong.saas.service.InstockService;
import com.xbongbong.saas.service.InventoryService;
import com.xbongbong.saas.service.InvoiceService;
import com.xbongbong.saas.service.OpportunityService;
import com.xbongbong.saas.service.OutstockService;
import com.xbongbong.saas.service.ProductService;
import com.xbongbong.saas.service.ProductionOrderService;
import com.xbongbong.saas.service.PurchaseInvoiceService;
import com.xbongbong.saas.service.PurchaseService;
import com.xbongbong.saas.service.QuotationService;
import com.xbongbong.saas.service.ReturnedPurchaseService;
import com.xbongbong.saas.service.ScoreRangeService;
import com.xbongbong.saas.service.TransferService;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.saas.service.WorkOrderFormService;
import com.xbongbong.saas.service.WorkOrderService;
import com.xbongbong.saas.service.toolbox.help.AnalysisSaasDataListHelp;
import com.xbongbong.saas.service.toolbox.help.AttrDecimalPrecisionHelper;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.toolbox.help.OnlyInsertDBHelp;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserConfigEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.UserConfigEnum;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserConfigModel;
import com.xbongbong.sys.model.UserDepartmentModel;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.util.AddressUtil;
import com.xbongbong.workorder.service.WorkOrderBasicService;
import com.xbongbong.workorder.service.WorkOrderStageService;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.collapse.CollapseBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.IndexBoost;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerOrDefaultFromFormData;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.existsQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author haibin.zhang
 * @version v1.0
 * @date 2019/1/23 11:31
 * @since v1.0
 */
@Component
public class SaasListHelp {
    private static final Logger Log = LoggerFactory.getLogger(SaasListHelp.class);
    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private CustomerFocusModel customerFocusModel;
    @Resource
    private ProductService productService;
    @Resource
    private EsHelper esHelper;
    @Resource
    private ScoreRangeModel scoreRangeModel;
    @Resource
    private OpportunityFocusModel opportunityFocusModel;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private SaasAddHelp saasAddHelp;
    @Resource
    private SaasHelp saasHelp;
    @Resource
    private OpportunityProductModel opportunityProductModel;
    @Resource
    private PurchaseProductModel purchaseProductModel;
    @Resource
    private ReturnedPurchaseProductModel returnedPurchaseProductModel;
    @Resource
    private InstockProductModel instockProductModel;
    @Resource
    private OutstockProductModel outstockProductModel;
    @Resource
    private AssembleProductModel assembleProductModel;
    @Resource
    private InventoryProductModel inventoryProductModel;
    @Resource
    private TransferProductModel transferProductModel;
    @Resource
    private PushModel pushModel;
    @Resource
    private ContractService contractService;
    @Resource
    private TagLinkModel tagLinkModel;
    @Resource
    private WorkOrderProductModel workOrderProductModel;
    @Resource
    private WorkOrderFlowNodeModel workOrderFlowNodeModel;
    @Resource
    private UserModel userModel;
    @Resource
    private SpecificationModel specificationModel;
    @Resource
    private WorkOrderListDataPermissionHelp workOrderListDataPermissionHelp;
    @Resource
    private WorkOrderBasicService workOrderBasicService;
    @Resource
    private ListGroupHelp listGroupHelp;
    @Resource
    private PublicGroupHelp publicGroupHelp;
    @Resource
    private PaasListGroupModel paasListGroupModel;
    @Resource
    private WorkOrderFormService workOrderFormService;
    @Resource
    private DataDictionaryModel dataDictionaryModel;
    @Resource
    private AnalysisSaasDataListHelp analysisSaasDataListHelp;
    @Resource
    private InvoiceService invoiceService;
    @Resource
    private WorkOrderListGroupHelp workOrderListGroupHelp;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private AttrDecimalPrecisionHelper attrDecimalPrecisionHelper;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private WorkOrderTemplateModel workOrderTemplateModel;
    @Resource
    private ProductListHelp productListHelp;
    @Resource
    private OpportunityService opportunityService;
    @Resource
    private CallCenterCommonService callCenterCommonService;
    @Resource
    private WorkOrderStageService workOrderStageService;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;
    @Resource
    private PaasFormService paasFormService;
    @Resource
    private CustomerConditionServiceImpl customerConditionService;
    @Resource
    private FormDataListSearchHelp formDataListSearchHelp;
    @Resource
    private QuotationProductModel quotationProductModel;
    @Resource
    private QuotationService quotationService;
    @Resource
    private ContractModel contractModel;
    @Resource
    private ContractDao contractDao;
    @Resource
    private PaymentModel paymentModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaymentSheetModel paymentSheetModel;
    @Resource
    private InvoiceRelationshipModel invoiceRelationshipModel;
    @Resource
    private PurchaseInvoiceRelationshipModel purchaseInvoiceRelationshipModel;
    @Resource
    private InvoiceModel invoiceModel;
    @Resource
    private FundHelp fundHelp;
    @Resource
    private PurchaseInvoiceService purchaseInvoiceService;
    @Resource
    private PurchaseService purchaseService;
    @Resource
    private ReturnedPurchaseService returnedPurchaseService;
    @Resource
    private AssembleService assembleService;
    @Resource
    private InstockService instockService;
    @Resource
    private OutstockService outstockService;
    @Resource
    private BomBillService bomBillService;
    @Resource
    private ProductionOrderService productionOrderService;
    @Resource
    private WorkOrderService workOrderService;
    @Resource
    private InventoryService inventoryService;
    @Resource
    private TransferService transferService;
    @Resource
    private ProductBaseInfoModel productBaseInfoModel;
    @Resource
    private BomProductModel bomProductModel;
    @Resource
    private ProductionOrderProductModel productionOrderProductModel;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private FormDataValidateProductHelp formDataValidateProductHelp;
    @Resource
    private PromotionProductModel promotionProductModel;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private FundSetService fundSetService;
    @Resource
    private RelativeProductHelp relativeProductHelp;
    @Resource
    private ScoreRangeService scoreRangeService;
    @Resource
    private CreditLimitService creditLimitService;
    @Resource
    private MarketManagementBusinessHelp marketManagementBusinessHelp;
    @Resource
    private CustomerStatementProductModel customerStatementProductModel;
    @Resource
    private CallCenterService callCenterService;
    @Resource
    private PurchaseBalanceModel purchaseBalanceModel;
    @Resource
    private InstockModel instockModel;
    @Resource
    private UserHelp userHelp;
    @Resource
    private ContractProductService contractProductService;
    @Resource
    private SupplierProductModel supplierProductModel;
    @Resource
    private SmartReplenishmentModel smartReplenishmentModel;
    @Resource
    private CostAdjustProductModel costAdjustProductModel;
    @Resource
    private ContactModel contactModel;
    @Resource
    private SaasLinkProductHelp saasLinkProductHelp;

    @Resource
    private UserConfigModel userConfigModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private UserDepartmentModel userDepartmentModel;
    @Resource
    private ContractUserModel contractUserModel;

    @Resource
    private DetailTabDataPermissionHelp detailTabDataPermissionHelp;
    @Resource
    private Map<Integer, BusinessConditionService> businessConditionMap;



    /**
     * 表单数据渲染
     * @param formDataEsListVO
     * @param explainMap
     * @throws XbbException
     */
    public void analysisSaasDataList(PaasFormDataEsListVO formDataEsListVO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        analysisSaasDataListHelp.analysisSaasDataList(formDataEsListVO,explainMap);
    }

    public void analysisSaasDataList(PrePaymentBalanceListVO prePaymentBalanceListVO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        analysisSaasDataListHelp.analysisSaasDataList(prePaymentBalanceListVO,explainMap);
    }

    public void analysisSaasDataList(PaymentSheetDateEsListVO paymentSheetDateEsListVO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        analysisSaasDataListHelp.analysisSaasDataList(paymentSheetDateEsListVO,explainMap);
    }
    public void analysisSaasDataList4Web(PaasFormDataEsListVO formDataEsListVO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        analysisSaasDataListHelp.analysisSaasDataList4Web(formDataEsListVO,explainMap);
    }
    /**
     * 工单字段渲染
     * @param workOrderDataEsListVO
     * @param explainMap
     * @throws XbbException
     */
    public void analysisSaasDataList(WorkOrderDataEsListVO workOrderDataEsListVO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        analysisSaasDataListHelp.analysisSaasDataList(workOrderDataEsListVO,explainMap);
    }
    /**
     * 工单字段渲染
     * @param workOrderDataEsListVO
     * @param explainMap
     * @throws XbbException
     */
    public void analysisSaasDataList4Web(WorkOrderDataEsListVO workOrderDataEsListVO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        analysisSaasDataListHelp.analysisSaasDataList4Web(workOrderDataEsListVO,explainMap);
    }
    /**
     * 工单全部字段渲染
     * @param workOrderDataEsListVO
     * @param formIdAndExplainMap
     * @throws XbbException
     */
    public void analysisSaasDataAllList(WorkOrderDataEsListVO workOrderDataEsListVO, Map<Long, Map<String,FieldAttrEntity>> formIdAndExplainMap) throws XbbException {
        analysisSaasDataListHelp.analysisSaasDataAllList(workOrderDataEsListVO, formIdAndExplainMap);
    }

    /**
     * 工单全部字段渲染
     * @param workOrderDataEsListVO
     * @param formIdAndExplainMap
     * @throws XbbException
     */
    public void analysisSaasDataAllList4Web(WorkOrderDataEsListVO workOrderDataEsListVO, Map<Long, Map<String,FieldAttrEntity>> formIdAndExplainMap) throws XbbException {
        analysisSaasDataListHelp.analysisSaasDataAllList4Web(workOrderDataEsListVO, formIdAndExplainMap);
    }

    public Integer getBusinessType(Integer businessType) {
        return ListBusinessTypeEnum.getBusinessType(businessType);

    }

    /**
     * 设置saas负责人
     * 仅app
     * @param formDataEsListVO
     * @param corpid
     * @param businessType
     */
    public void setMainUser(PaasFormDataEsListVO formDataEsListVO, String corpid, Integer businessType, Boolean isPublic) {
        List<PaasFormDataEntityExt> list = formDataEsListVO.getPaasFormDataESList();
        if (list == null || list.isEmpty()) {
            return;
        }
        List<Long> dataIdList = new ArrayList<>();
        for (PaasFormDataEntityExt entity : list) {
            dataIdList.add(entity.getDataId());
        }
        Map<Long,String> mainUserMap = userTeamService.getMainUserMap(dataIdList,corpid,businessType,isPublic);
        for (PaasFormDataEntityExt entity : list){
            JSONObject data = entity.getData();
            data.put(FieldTypeEnum.OWNERID.getAlias(),mainUserMap.getOrDefault(entity.getDataId(),""));
            entity.setData(data);
        }
        formDataEsListVO.setPaasFormDataESList(list);
    }

    /**
     * 处理选择关联业务时的表头返回
     *
     * @param fieldList          字段列表
     * @param sourceBusinessType 选择产品的源业务类型
     * @param type               区分成品入库/退料入库
     * @author lcx
     * @date 2019-02-18 20:24
     */
    public List<String> dealFieldList(List<String> fieldList, Integer businessType, Integer sourceBusinessType, Integer type) throws XbbException {
        if (fieldList == null || businessType == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002);
        }
        if (sourceBusinessType == null) {
            return fieldList;
        }
        List<String> result = new ArrayList<>(fieldList);
        XbbRefTypeEnum selectedBusiness = XbbRefTypeEnum.getByCode(businessType);
        switch (selectedBusiness) {
            case RETURNED_PURCHASE:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.OUTSTOCK.getCode())) {
                    result.removeIf(fieldStr -> !Objects.equals(fieldStr, PurchaseEnum.SHEET_NO.getAttr()));
                }
                break;
            case CONTRACT:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.OUTSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.INSTOCK.getCode())) {
                    result.removeIf(fieldStr -> !(Objects.equals(fieldStr, ContractEnum.CONTRACT_NO.getAttr()) ||
                            Objects.equals(fieldStr, ContractEnum.NAME.getAttr()) || Objects.equals(fieldStr,ContractEnum.SIGN_TIME.getAttr())));
                }
                result.add(OrderEnum.COUPON_ID.getAttr());
                break;
            case TRANSFER:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.OUTSTOCK.getCode())) {
                    result.removeIf(fieldStr -> !(Objects.equals(fieldStr, TransferEnum.SHEET_NO.getAttr()) ||
                            Objects.equals(fieldStr, TransferEnum.OUT_WAREHOUSE_ID.getAttr()) ||
                            Objects.equals(fieldStr, TransferEnum.OUT_WAREHOUSE_ID_LINKED_TEXT.getAttr())));
                } else if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.INSTOCK.getCode())) {
                    result.removeIf(fieldStr -> !(Objects.equals(fieldStr, TransferEnum.INTO_WAREHOUSE_ID.getAttr()) ||
                            Objects.equals(fieldStr, TransferEnum.INTO_WAREHOUSE_ID_LINKED_TEXT.getAttr()) ||
                            Objects.equals(fieldStr, TransferEnum.SHEET_NO.getAttr())));
                }
                break;
            case PRODUCTION_ORDER:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.OUTSTOCK.getCode())) {
                    result.removeIf(fieldStr -> !(Objects.equals(fieldStr, ProductionOrderEnum.SHEET_NO.getAttr()) ||
                            Objects.equals(fieldStr, ProductionOrderEnum.OUT_WAREHOUSE_ID.getAttr()) ||
                            Objects.equals(fieldStr, ProductionOrderEnum.OUT_WAREHOUSE_ID_LINK_TEXT.getAttr())));
                } else if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.INSTOCK.getCode())) {
                    if (Objects.equals(type, InstockTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode())) {
                        // 退料入库的仓库是生产单的物料出库仓库
                        result.removeIf(fieldStr -> !(Objects.equals(fieldStr, ProductionOrderEnum.SHEET_NO.getAttr()) ||
                                Objects.equals(fieldStr, ProductionOrderEnum.OUT_WAREHOUSE_ID.getAttr()) ||
                                Objects.equals(fieldStr, ProductionOrderEnum.OUT_WAREHOUSE_ID_LINK_TEXT.getAttr())));
                    } else {
                        result.removeIf(fieldStr -> !(Objects.equals(fieldStr, ProductionOrderEnum.SHEET_NO.getAttr()) ||
                                Objects.equals(fieldStr, ProductionOrderEnum.INTO_WAREHOUSE_ID.getAttr()) ||
                                Objects.equals(fieldStr, ProductionOrderEnum.INTO_WAREHOUSE_ID_LINK_TEXT.getAttr())));
                    }
                }
                break;
            case REFUND:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.INSTOCK.getCode())) {
                    result.removeIf(fieldStr -> !(Objects.equals(fieldStr, RefundEnum.REFUND_NO.getAttr()) ||
                            Objects.equals(fieldStr, RefundEnum.REFUND_NAME.getAttr())));
                }
                break;
            case PAYMENT_SHEET:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.INVOICE.getCode())) {
                    result.removeIf(fieldStr -> (Objects.equals(fieldStr, PaymentSheetEnum.BELONG_ID.getAttr())));
                }
                break;
            case CUSTOMER_MANAGEMENT:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.FULL_DISCOUNT_COUPON.getCode()) || Objects.equals(sourceBusinessType, XbbRefTypeEnum.SPECIAL_GOODS.getCode())) {
                    result = new ArrayList<>();
                    result.add(DistributorEnum.NAME.getAttr());
                    result.add(DistributorEnum.NAME_SHORT.getAttr());
                    result.add(DistributorEnum.AREA.getAttr());
                    result.add(DistributorEnum.SCALE.getAttr());
                }
                break;
            default:
                break;
        }
        return result;
    }

    /**
     * 设置列表页操作栏
     *
     * @param formDataEsListVO 回参
     * @param formDataListDTO  前端传入的数据DTO
     */
    public void setOption(PaasFormDataEsListVO formDataEsListVO, FormDataListDTO formDataListDTO) throws XbbException {
        // 获取参数
        String corpid = formDataListDTO.getCorpid();
        Integer businessType = formDataListDTO.getBusinessType();
        Integer subBusinessType = formDataListDTO.getSubBusinessType();
        Long listGroupId = formDataListDTO.getListGroupId();
        Integer distributorMark = formDataListDTO.getDistributorMark();

        List<PaasFormDataEntityExt> list = formDataEsListVO.getPaasFormDataESList();
        List<Long> dataIdList = new ArrayList<>();
        for (PaasFormDataEntityExt entity : list) {
            dataIdList.add(entity.getId());
        }
        dataIdList.add(-1L);
        //表头

        /**
         有三种情况下新建发票按钮需要隐藏或者置灰
         （1）“手动创建应收”模式下产生的应收款/回款单，在开票模式下新建发票，隐藏
         （2）开票模式下生成的应收款/回款单，“手动创建应收”模式下新建发票，置灰
         （3）开票模式下生成的应收款/回款单，开票模式下新建发票，隐藏
         总结：开票模式时，隐藏新建发票按钮（隐藏操作即不塞入发票按钮即可）；开票模式生成的数据，在其他模式时（非开票模式），新建发票按钮置灰
         */
        //当前系统所在模式
        Long currentModelType = fundSetService.getModelType(corpid, XbbRefTypeEnum.CRM);
        ListOptionPackagePojo listOptionPackagePojo = setOptionBase(dataIdList, formDataListDTO, formDataEsListVO, currentModelType);

        List<FieldAttrEntity> headList = formDataEsListVO.getHeadList();
        setHeadList(headList,listOptionPackagePojo,subBusinessType,businessType);
        for (FieldAttrEntity fieldAttrEntity : headList){
            if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LINK_BUSINESS_SINGLE.getType())
                    || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LINK_BUSINESS_MULTI.getType())) {
                LinkDetailPojo linkDetail = new LinkDetailPojo();
                linkDetail.setBusinessType(fieldAttrEntity.getLinkedType());
                linkDetail.setSubBuisenssType(fieldAttrEntity.getLinkedType());
                linkDetail.setSaasMark(SaasMarkEnum.SAAS.getCode());
                fieldAttrEntity.setLinkDetail(linkDetail);
            }
        }

        Map<String, FieldAttrEntity> explainMap = new HashMap<>();
        if (Objects.equals(businessType, XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), formDataListDTO.getCorpid());
            explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains());
        }
        // 客户，联系人，访客计划
        if(Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CONTACT.getCode()) ||
                Objects.equals(businessType, XbbRefTypeEnum.COMMUNICATE_PLAN.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())){
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType4Distributor(businessType, formDataListDTO.getCorpid(), distributorMark);
            explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains());
        }

        RelativeProductExplainVO relativeProductExplainVO = saasAddHelp.getRelativeProductExplainsFromDB(corpid, subBusinessType, listGroupId);

        if (Objects.equals(businessType,XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode())){
            List<PaasFormDataEntityExt>  paasFormDataESList = new ArrayList<>();
            Map<Long,List<WaitOutstockProductPojo>> waitOutstockProductMap = listOptionPackagePojo.getWaitOutstockProductMap();
            List<PurchaseProductEntity> purchaseProductEntity = formDataListDTO.getPurchaseProductEntityList();
            Map<Long , PaasFormDataEntityExt> paasFormDataEntity = new HashMap<>();
            for (PaasFormDataEntityExt paasFormDataEntityExt : list){
                //封装穿透所需要的参数
                JSONArray purchaseNoArray = new JSONArray();
                JSONObject purchaseNo = new JSONObject();
                purchaseNo.put("name",paasFormDataEntityExt.getSerialNo());
                purchaseNo.put("id",paasFormDataEntityExt.getDataId());
                purchaseNo.put("businessType",XbbRefTypeEnum.PURCHASE.getCode());
                purchaseNo.put("saasMark",SaasMarkEnum.SAAS.getCode());
                purchaseNoArray.add(purchaseNo);
                JSONArray purchaseNameArray = new JSONArray();
                JSONObject purchaseName = new JSONObject();
                purchaseName.put("name",paasFormDataEntityExt.getData().get(WaitInstockEnum.PURCHASE_NAME.getAttr()));
                purchaseName.put("id",paasFormDataEntityExt.getDataId());
                purchaseName.put("businessType",XbbRefTypeEnum.PURCHASE.getCode());
                purchaseName.put("saasMark",SaasMarkEnum.SAAS.getCode());
                purchaseNameArray.add(purchaseName);
                paasFormDataEntityExt.getData().put(WaitInstockEnum.SHEET_NO.getAttr(),purchaseNoArray);
                paasFormDataEntityExt.getData().put(WaitInstockEnum.PURCHASE_NAME.getAttr(),purchaseNameArray);
                paasFormDataEntity.put(paasFormDataEntityExt.getId(),paasFormDataEntityExt);
            }
            //将采购合同数据与产品数据封装到一起
            for (PurchaseProductEntity purchaseProduct : purchaseProductEntity){
                PaasFormDataEntityExt entity = new PaasFormDataEntityExt();
                if (Objects.nonNull(paasFormDataEntity.get(purchaseProduct.getPurchaseSheetId()))){
                    BeanUtil.copyProperties(paasFormDataEntity.get(purchaseProduct.getPurchaseSheetId()), entity);
                    if (Objects.nonNull(entity)){
                        setOptionValue(entity, formDataListDTO,listOptionPackagePojo, businessType, subBusinessType, listGroupId, explainMap, relativeProductExplainVO);
                        JSONObject data = (JSONObject) entity.getData().clone();
                        WaitOutstockProductPojo waitOutstockProduct = waitOutstockProductMap.get(purchaseProduct.getPurchaseSheetId())
                                .stream().filter(p ->Objects.equals(purchaseProduct.getId(),p.getId())).findAny().orElse(new WaitOutstockProductPojo());
                        data.put(WaitInstockEnum.PRODUCT_IMGS.getAttr(),waitOutstockProduct.getProductThumnail());
                        JSONArray productNameArray = new JSONArray();
                        JSONObject productName = new JSONObject();
                        productName.put("name",waitOutstockProduct.getProductName());
                        productName.put("id",purchaseProduct.getParentId());
                        productName.put("businessType",XbbRefTypeEnum.PRODUCT.getCode());
                        productName.put("saasMark",SaasMarkEnum.SAAS.getCode());
                        productNameArray.add(productName);
                        JSONArray productNoArray = new JSONArray();
                        JSONObject productNo = new JSONObject();
                        productNo.put("name",waitOutstockProduct.getProductNo());
                        productNo.put("id",purchaseProduct.getParentId());
                        productNo.put("businessType",XbbRefTypeEnum.PRODUCT.getCode());
                        productNo.put("saasMark",SaasMarkEnum.SAAS.getCode());
                        productNoArray.add(productNo);
                        data.put(WaitInstockEnum.PRODUCT_NAME.getAttr(),productNameArray);
                        data.put(WaitInstockEnum.PRODUCT_NO.getAttr(),productNoArray);
                        data.put(WaitInstockEnum.SPECIFICATION.getAttr(),waitOutstockProduct.getSpecification());
                        data.put(WaitInstockEnum.UNIT.getAttr(),waitOutstockProduct.getUnit());
                        data.put(WaitInstockEnum.STOCK.getAttr(),waitOutstockProduct.getNum());
                        data.put(WaitInstockEnum.MEMO.getAttr(),waitOutstockProduct.getMemo());
                        data.put("transformUnitRate",waitOutstockProduct.getTransformUnitRate());
                        data.put("productId",waitOutstockProduct.getId());
                        data.put("linkId",waitOutstockProduct.getLinkId());
                        entity.setData(data);
                    }
                    paasFormDataESList.add(entity);
                }else {
                    Log.info("异常合同id为：" + purchaseProduct.getPurchaseSheetId().toString());
                }
            }
            formDataEsListVO.setPaasFormDataESList(paasFormDataESList);
        } else if (Objects.equals(businessType,XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_OUTSTOCK.getCode())){
            List<PaasFormDataEntityExt>  paasFormDataESList = new ArrayList<>();
            Map<Long,List<WaitOutstockProductPojo>> waitOutstockProductMap = listOptionPackagePojo.getWaitOutstockProductMap();
            List<ContractProductEntity> contractProductEntityList = formDataListDTO.getContractProductEntityList();
            Map<Long , PaasFormDataEntityExt> contractEntityExtMap = new HashMap<>();
            for (PaasFormDataEntityExt paasFormDataEntityExt : list){
                contractEntityExtMap.put(paasFormDataEntityExt.getId(),paasFormDataEntityExt);
            }
            for (ContractProductEntity contractProductEntity : contractProductEntityList){
                PaasFormDataEntityExt entity=new PaasFormDataEntityExt();
                if (Objects.nonNull(contractEntityExtMap.get(contractProductEntity.getContractId()))){
                    BeanUtil.copyProperties(contractEntityExtMap.get(contractProductEntity.getContractId()), entity);
                }
                if (Objects.nonNull(entity) && Objects.nonNull(entity.getData())){
                    setOptionValue(entity, formDataListDTO,listOptionPackagePojo, businessType, subBusinessType, listGroupId, explainMap, relativeProductExplainVO);
                    disabledButton(listOptionPackagePojo,businessType,entity, formDataListDTO.getLoginUser().getPermSet(), currentModelType);
                    JSONObject data = (JSONObject) entity.getData().clone();
                    //data.putAll(entity.getData());
                    //data=entity.getData();
                    WaitOutstockProductPojo waitOutstockProduct = waitOutstockProductMap.get(contractProductEntity.getContractId())
                            .stream().filter(p ->Objects.equals(contractProductEntity.getId(),p.getId())).findAny().orElse(new WaitOutstockProductPojo());
                    data.put(ProductEnum.PRODUCT_IMGS.getAttr(),waitOutstockProduct.getProductThumnail());
                    //处理产品穿透详情
                    JSONArray productNameArray = new JSONArray();
                    JSONObject productName = new JSONObject();
                    productName.put("name",waitOutstockProduct.getProductName());
                    productName.put("id",contractProductEntity.getParentId());
                    productName.put("businessType",XbbRefTypeEnum.PRODUCT.getCode());
                    productName.put("saasMark",SaasMarkEnum.SAAS.getCode());
                    productNameArray.add(productName);
                    JSONArray productNoArray = new JSONArray();
                    JSONObject productNo = new JSONObject();
                    productNo.put("name",waitOutstockProduct.getProductNo());
                    productNo.put("id",contractProductEntity.getParentId());
                    productNo.put("businessType",XbbRefTypeEnum.PRODUCT.getCode());
                    productNo.put("saasMark",SaasMarkEnum.SAAS.getCode());
                    productNoArray.add(productNo);
                    data.put(SelectProductEnum.PRODUCT_NAME.getAttr(),productNameArray);
                    data.put(SelectProductEnum.PRODUCT_NO.getAttr(),productNoArray);
                    data.put(SelectProductEnum.SPECIFICATION.getAttr(),waitOutstockProduct.getSpecification());
                    data.put(SelectProductEnum.UNIT.getAttr(),waitOutstockProduct.getUnit());
                    data.put(SelectProductEnum.WAIT_OUTSTOCK_NUM.getAttr(),waitOutstockProduct.getNum());
                    data.put(SelectProductEnum.STOCK.getAttr(),waitOutstockProduct.getStock());
                    data.put(SelectProductEnum.MEMO.getSaasAttr(),waitOutstockProduct.getMemo());
                    data.put(ProductEnum.ENABLE_MULTI_UNIT.getAttr(),waitOutstockProduct.getEnableMultiUnit());
                    data.put("transformUnitRate",waitOutstockProduct.getTransformUnitRate());
                    data.put("productId",waitOutstockProduct.getId());
                    //处理合同穿透信息
                    JSONArray contractNoArray = new JSONArray();
                    JSONObject contractNo = new JSONObject();
                    contractNo.put("name",entity.getSerialNo());
                    contractNo.put("id",entity.getDataId());
                    contractNo.put("businessType",XbbRefTypeEnum.CONTRACT.getCode());
                    contractNo.put("saasMark",SaasMarkEnum.SAAS.getCode());
                    contractNoArray.add(contractNo);
                    JSONArray contractNameArray = new JSONArray();
                    JSONObject contractName = new JSONObject();
                    contractName.put("name",data.get(ContractEnum.NAME.getAttr()));
                    contractName.put("id",entity.getDataId());
                    contractName.put("businessType",XbbRefTypeEnum.CONTRACT.getCode());
                    contractName.put("saasMark",SaasMarkEnum.SAAS.getCode());
                    contractNameArray.add(contractName);
                    data.put(ContractEnum.CONTRACT_NO.getAttr(),contractNoArray);
                    data.put(ContractEnum.NAME.getAttr(),contractNameArray);
                    entity.setData(data);
                }
                paasFormDataESList.add(entity);
            }
            formDataEsListVO.setPaasFormDataESList(paasFormDataESList);
        } else {
            for (PaasFormDataEntityExt entity : list){
                JSONObject data = entity.getData();
                disabledButton(listOptionPackagePojo,businessType,entity, formDataListDTO.getLoginUser().getPermSet(), currentModelType);

                setOptionValue(entity, formDataListDTO,listOptionPackagePojo, businessType, subBusinessType, listGroupId, explainMap, relativeProductExplainVO);

                if (listOptionPackagePojo.getCrossMonth()) {
                    if(Objects.equals(businessType,XbbRefTypeEnum.INVOICE.getCode())) {
                        entity.setCrossMonth(DateTimeUtil.getFirstDateOfThisMonth() > data.getLong(InvoiceEnum.INVOICE_DATE.getAttr()));
                    }else if(Objects.equals(businessType,XbbRefTypeEnum.PURCHASE_INVOICE.getCode())){
                        entity.setCrossMonth(DateTimeUtil.getFirstDateOfThisMonth() > data.getLong(PurchaseInvoiceEnum.INVOICE_DATE.getAttr()));
                    }
                }
                if (listOptionPackagePojo.getProductMap().containsKey(entity.getDataId())) {
                    JSONArray jsonArray = listOptionPackagePojo.getProductMap().get(entity.getDataId());
                    for (Object object : jsonArray) {
                        JSONObject jsonObject = (JSONObject) object;
                        if (jsonObject.containsKey(SubOptionTableHeadEnum.GUARANTEE_PRODUCE_DATE.getProp())) {
                            String produceDate = jsonObject.getString(SubOptionTableHeadEnum.GUARANTEE_PRODUCE_DATE.getProp());
                            if (Objects.isNull(produceDate) || produceDate.isEmpty()) {
                                data.remove(ListOptionEnum.GUARANTEE_SEARCH.getAttr());
                            }
                        }
                    }
                }
            }
        }
    }

    private void checkInvoiceOption(FormDataListDTO formDataListDTO,List<PaasFormDataEntityExt> list,ListOptionPackagePojo listOptionPackagePojo,XbbRefTypeEnum xbbRefTypeEnum) throws XbbException{
        Set<Long> purchaseOrContractIdList = new HashSet<>();
        Set<Long> refObjectIdList = new HashSet<>();
        Map<Long,Long> parentIdRefSubId = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //Set<Long> paymentSheetOrPaySheetSubIds = new HashSet<>();
        Set<String> uuidSet = new HashSet<>();
        Map<String,Long> parentIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,Double> purchaseOrContractInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,Double> purchaseOrContractAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,Double> purchaseOrContractUnInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,Double> paymentOrPayPlanInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,Double> paymentSheetOrPaySheetInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if(CollectionsUtil.isNotEmpty(list)) {
            for(PaasFormDataEntityExt entity : list){
                if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAYMENT) || Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAY_PLAN)){
                    if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAYMENT)){
                        purchaseOrContractIdList.add(FastJsonHelper.getLongOrDefaultFromFormData(entity.getData(),PaymentEnum.CONTRACT.getAttr(),0L));
                    }else if(Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAY_PLAN)){
                        purchaseOrContractIdList.add(FastJsonHelper.getLongOrDefaultFromFormData(entity.getData(),PayPlanEnum.LINK_PURCHASE.getAttr(),0L));
                    }
                    refObjectIdList.add(entity.getId());
                }else if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAYMENT_SHEET) || Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_SHEET)){
                    JSONArray contractOrPurchaseArray = new JSONArray();
                    if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAYMENT_SHEET)){
                        contractOrPurchaseArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(entity.getData(),PaymentSheetEnum.CONTRACT.getAttr(),new JSONArray());
                    }else if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_SHEET)){
                        contractOrPurchaseArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(entity.getData(),PaySheetEnum.LINK_PURCHASE.getAttr(),new JSONArray());
                    }
                    if(contractOrPurchaseArray.size()>BasicConstant.ZERO) {
                        purchaseOrContractIdList.addAll(JSONArray.parseArray(contractOrPurchaseArray.toJSONString(), Long.class));
                    }
                    if(Objects.equals(entity.getAlone(),SheetAloneEnum.PARENT.getCode())) {
                        if (Objects.nonNull(entity.getUuid())) {
                            uuidSet.add(entity.getUuid());
                            parentIdMap.put(entity.getUuid(),entity.getId());
                        }
                    }else {
                        refObjectIdList.add(entity.getId());
                    }
                }
            }
        }

        if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAYMENT_SHEET) || Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_SHEET)){
            List<PaasFormDataEntityExt> paymentSheetOrPaySheetEntityExt = fundHelp.getChildEsDataListByParentUuids(xbbRefTypeEnum,formDataListDTO.getCorpid(),uuidSet,null,null);
            if(CollectionsUtil.isNotEmpty(paymentSheetOrPaySheetEntityExt)){
                for(PaasFormDataEntityExt paasFormDataEntityExt : paymentSheetOrPaySheetEntityExt){
                    refObjectIdList.add(paasFormDataEntityExt.getId());
                    if(parentIdMap.containsKey(paasFormDataEntityExt.getUuid())){
                        Long parentId = parentIdMap.getOrDefault(paasFormDataEntityExt.getUuid(),0L);
                        parentIdRefSubId.put(paasFormDataEntityExt.getId(),parentId);
                    }
                }
            }
        }

        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",formDataListDTO.getCorpid());
        param.put("del",BasicConstant.ZERO);
        if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAY_PLAN) || Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_SHEET)) {
            //查询关联的数据 或合同的数据
            List<PurchaseEntityExt> purchaseEntityExtList = null;
            if(CollectionsUtil.isNotEmpty(purchaseOrContractIdList)) {
                purchaseEntityExtList = purchaseModel.getPurchaseListByIdIn(formDataListDTO.getCorpid(), new ArrayList<>(purchaseOrContractIdList));
            }
            if(CollectionsUtil.isNotEmpty(purchaseEntityExtList)) {
                for(PurchaseEntityExt purchaseEntityExt : purchaseEntityExtList){
                    double amount = getDoubleOrDefaultFromFormData(purchaseEntityExt.getData(),PurchaseEnum.TOTAL_MONEY.getAttr(),0D);
                    saasSaveHelp.addMapNormal(purchaseOrContractAmountMap,purchaseEntityExt.getId(),amount);
                }
            }
            //查询采购合同开票 和 红冲金额
            param.put("purchaseIdIn", purchaseOrContractIdList);
            param.put("isCancel",BasicConstant.ZERO);
            List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationshipEntities = purchaseInvoiceRelationshipModel.findEntitys(param);
            if(CollectionsUtil.isNotEmpty(purchaseInvoiceRelationshipEntities)) {
                for (PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : purchaseInvoiceRelationshipEntities) {
                    if (!Objects.equals(purchaseInvoiceRelationshipEntity.getPurchaseId(), 0D)) {
                        saasSaveHelp.addMapNormal(purchaseOrContractInvoiceAmountMap, purchaseInvoiceRelationshipEntity.getPurchaseId(), purchaseInvoiceRelationshipEntity.getMoney());
                    }
                }
            }

            Iterator<Map.Entry<Long,Double>> iterator = purchaseOrContractAmountMap.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry<Long,Double> it = iterator.next();
                Long purchaseId = it.getKey();
                double amount = it.getValue();
                double unInvoiceAmount = Arith.sub(amount,purchaseOrContractInvoiceAmountMap.getOrDefault(purchaseId,0D));
                saasSaveHelp.addMapNormal(purchaseOrContractUnInvoiceAmountMap,purchaseId,unInvoiceAmount);
            }
            if(purchaseOrContractUnInvoiceAmountMap.size()>BasicConstant.ZERO){
                listOptionPackagePojo.setContractLeftInvoiceAmountMap(purchaseOrContractUnInvoiceAmountMap);
            }
            //查询回款单或应收款的开票金额
            param.clear();
            param.put("corpid",formDataListDTO.getCorpid());
            param.put("del",BasicConstant.ZERO);
            if(Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAY_PLAN)){
                param.put("payPlanIdIn",refObjectIdList);
            }else if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_SHEET)){
                param.put("paySheetIdIn",refObjectIdList);
            }
            param.put("isCancel",BasicConstant.ZERO);
            List<PurchaseInvoiceRelationshipEntity> entitys = purchaseInvoiceRelationshipModel.findEntitys(param);
            if(CollectionsUtil.isNotEmpty(entitys)){
                for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : entitys){
                    if(Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAY_PLAN)){
                        saasSaveHelp.addMapNormal(paymentOrPayPlanInvoiceAmountMap,purchaseInvoiceRelationshipEntity.getPayPlanId(),purchaseInvoiceRelationshipEntity.getMoney());
                        listOptionPackagePojo.setPaymentIdInvoiceAmountMap(paymentOrPayPlanInvoiceAmountMap);
                    }else if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_SHEET)){
                        if(parentIdRefSubId.containsKey(purchaseInvoiceRelationshipEntity.getPaySheetId())){
                            Long paySheetId = parentIdRefSubId.get(purchaseInvoiceRelationshipEntity.getPaySheetId());
                            saasSaveHelp.addMapNormal(paymentSheetOrPaySheetInvoiceAmountMap,paySheetId,purchaseInvoiceRelationshipEntity.getMoney());
                        }else {
                            saasSaveHelp.addMapNormal(paymentSheetOrPaySheetInvoiceAmountMap,purchaseInvoiceRelationshipEntity.getPaySheetId(),purchaseInvoiceRelationshipEntity.getMoney());

                        }
                        listOptionPackagePojo.setPaymentIdInvoiceAmountMap(paymentSheetOrPaySheetInvoiceAmountMap);
                    }
                }
            }

        }else if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAYMENT) || Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAYMENT_SHEET)){
            //查询关联的数据 或合同的数据
            List<ContractEntityExt> contractEntityExtList = null;
            if(CollectionsUtil.isNotEmpty(purchaseOrContractIdList)) {
                contractEntityExtList = contractModel.findEntitysByIdIn(formDataListDTO.getCorpid(), BasicConstant.ZERO, new ArrayList<>(purchaseOrContractIdList));
            }
            if(CollectionsUtil.isNotEmpty(contractEntityExtList)) {
                for(ContractEntityExt contractEntityExt : contractEntityExtList){
                    double amount = getDoubleOrDefaultFromFormData(contractEntityExt.getData(),ContractEnum.AMOUNT.getAttr(),0D);
                    saasSaveHelp.addMapNormal(purchaseOrContractAmountMap,contractEntityExt.getId(),amount);
                }
            }

            //查询采购合同开票 和 红冲金额
            param.put("contractIdIn", purchaseOrContractIdList);
            param.put("isCancel",BasicConstant.ZERO);
            List<InvoiceRelationshipEntity> invoiceRelationshipEntities = invoiceRelationshipModel.findEntitys(param);
            if(CollectionsUtil.isNotEmpty(invoiceRelationshipEntities)) {
                for (InvoiceRelationshipEntity invoiceRelationshipEntity : invoiceRelationshipEntities) {
                    if (!Objects.equals(invoiceRelationshipEntity.getContractId(), 0D)) {
                        saasSaveHelp.addMapNormal(purchaseOrContractInvoiceAmountMap, invoiceRelationshipEntity.getContractId(), invoiceRelationshipEntity.getMoney());
                    }
                }
            }

            Iterator<Map.Entry<Long,Double>> iterator = purchaseOrContractAmountMap.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry<Long,Double> it = iterator.next();
                Long contractId = it.getKey();
                double amount = it.getValue();
                double unInvoiceAmount = Arith.sub(amount,purchaseOrContractInvoiceAmountMap.getOrDefault(contractId,0D));
                saasSaveHelp.addMapNormal(purchaseOrContractUnInvoiceAmountMap,contractId,unInvoiceAmount);
            }
            if(purchaseOrContractUnInvoiceAmountMap.size()>BasicConstant.ZERO){
                listOptionPackagePojo.setContractLeftInvoiceAmountMap(purchaseOrContractUnInvoiceAmountMap);
            }
            //查询回款单或应收款的开票金额
            param.clear();
            param.put("corpid",formDataListDTO.getCorpid());
            param.put("del",BasicConstant.ZERO);
            if(Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT)){
                param.put("paymentIdIn",refObjectIdList);
            }else if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAYMENT_SHEET)){
                param.put("paymentSheetIdIn",refObjectIdList);
            }
            param.put("isCancel",BasicConstant.ZERO);
            List<InvoiceRelationshipEntity> entitys = invoiceRelationshipModel.findEntitys(param);
            if(CollectionsUtil.isNotEmpty(entitys)){
                for(InvoiceRelationshipEntity invoiceRelationshipEntity : entitys){
                    if(Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT)){
                        saasSaveHelp.addMapNormal(paymentOrPayPlanInvoiceAmountMap,invoiceRelationshipEntity.getPaymentId(),invoiceRelationshipEntity.getMoney());
                        listOptionPackagePojo.setPaymentIdInvoiceAmountMap(paymentOrPayPlanInvoiceAmountMap);
                    }else if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAYMENT_SHEET)){
                        if(parentIdRefSubId.containsKey(invoiceRelationshipEntity.getPaymentSheetId())){
                            Long paymentSheetId = parentIdRefSubId.get(invoiceRelationshipEntity.getPaymentSheetId());
                            saasSaveHelp.addMapNormal(paymentSheetOrPaySheetInvoiceAmountMap,paymentSheetId,invoiceRelationshipEntity.getMoney());
                        }else {
                            saasSaveHelp.addMapNormal(paymentSheetOrPaySheetInvoiceAmountMap,invoiceRelationshipEntity.getPaymentSheetId(),invoiceRelationshipEntity.getMoney());

                        }
                        listOptionPackagePojo.setPaymentIdInvoiceAmountMap(paymentSheetOrPaySheetInvoiceAmountMap);
                    }
                }
            }


        }
    }
    /**
     * 回款列表设置是否可开票相关
     * @param formDataListDTO 列表入参
     * @param list 数据列表（暨回款列表）
     * @param listOptionPackagePojo 列表操作封装类
     * @throws XbbException xbbException
     */
    private void paymentCheckInvoiceOption(FormDataListDTO formDataListDTO, List<PaasFormDataEntityExt> list, ListOptionPackagePojo listOptionPackagePojo,XbbRefTypeEnum xbbRefTypeEnum) throws XbbException {
        List<Long> contractIdList = new ArrayList<>();
        List<Long> refObjectIdList = new ArrayList<>();
        Set<String> uuids = new HashSet<>();
        Map<Long, Set<Long>> parentIdToChildPaymentSheetIds = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Long> parentIds = new HashSet<>();
        if(CollectionsUtil.isNotEmpty(list)) {
            for (PaasFormDataEntityExt entity : list) {
                refObjectIdList.add(entity.getId());
                if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT)) {
                    contractIdList.add(FastJsonHelper.getLongOrDefaultFromFormData(entity.getData(), PaymentEnum.CONTRACT.getAttr(), 0L));
                } else if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT_SHEET)) {
                    uuids.add(entity.getUuid());
                    List<Object> contractIds = saasUpdateHelp.getListFromFormData(entity.getData(), PaymentSheetEnum.CONTRACT.getAttr());
                    if (CollectionsUtil.isNotEmpty(contractIds)) {
                        saasUpdateHelp.getListFromFormData(entity.getData(), PaymentSheetEnum.CONTRACT.getAttr());
                    }
                    List<Long> dataIdStrList = JSONArray.parseArray(JSONArray.toJSONString(contractIds), Long.class);
                    contractIdList.addAll(dataIdStrList);
                }
                parentIds.add(entity.getId());
            }
        }
        if (contractIdList.isEmpty()){
            if(!Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAYMENT_SHEET)){
                return;
            }
        }
        // 查找关联合同的开票金额
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", formDataListDTO.getCorpid()));
        if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT)) {
            boolQueryBuilder.filter(termsQuery("data."+InvoiceEnum.PAYMENT_ID.getAttr(),refObjectIdList));
        } else if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT_SHEET)) {
            assemblePaymentSheetRelation(formDataListDTO, uuids, list, parentIdToChildPaymentSheetIds, refObjectIdList, XbbRefTypeEnum.PAYMENT_SHEET);
            boolQueryBuilder.filter(termsQuery("data."+InvoiceEnum.PAYMENT_SHEET_ID.getAttr(),refObjectIdList));
        }
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termQuery("data." + InvoiceEnum.IS_CANCEL.getAttr(),0));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_INVOICE.getType()));
        sourceBuilder.query(boolQueryBuilder);
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, PaasConstant.ES_MAX_PAGE_SIZE);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_INVOICE.getIndex());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest, PaasFormDataEntityExt.class);
        // 关联发票列表
        List<PaasFormDataEntityExt> invoiceList = esEntities.getContent();
        List<Long> invoiceIdList = new ArrayList<>();
        invoiceList.forEach(item ->{
            invoiceIdList.add(item.getId());
        });
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",formDataListDTO.getCorpid());
        param.put("invoiceIdIn",invoiceIdList);
        param.put(InvoiceEnum.IS_CANCEL.getAttr(),BasicConstant.ZERO);
        param.put("del",BasicConstant.ZERO);
        List<InvoiceRelationshipEntity> invoiceRelationshipEntities = invoiceRelationshipModel.getByParam(param);
        //红冲部分的金额
        Map<Long, Double> refInvoiceMap = invoiceService.getRedTotalMoneyByIdIn(invoiceIdList,null,formDataListDTO.getCorpid());
        Map<Long,Double> refRealInvoiceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        invoiceRelationshipEntities.forEach(item ->{
            double invoiceAmount = item.getMoney();

            if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT)) {
                refRealInvoiceMap.merge(item.getPaymentId(),invoiceAmount,(a, b) -> a + b);
            } else if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT_SHEET)) {
                refRealInvoiceMap.merge(item.getPaymentSheetId(),invoiceAmount,(a, b) -> a + b);
            }
        });
        Iterator<Map.Entry<Long,Double>> it = refRealInvoiceMap.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<Long,Double> entry = it.next();
            Long key = entry.getKey();
            if(refInvoiceMap.containsKey(key)){
                double realInvoice = refRealInvoiceMap.getOrDefault(key,0D) + refInvoiceMap.getOrDefault(key,0D);
                refRealInvoiceMap.put(key,realInvoice);
            }
        }



        // 查找关联合同
        Map<Long, Double> contractAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 合同剩余可开票金额
        Map<Long,Double> contractLeftInvoiceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if(CollectionsUtil.isNotEmpty(contractIdList)) {
            SearchSourceBuilder sourceBuilder1 = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder1 = boolQuery();
            boolQueryBuilder1.filter(termQuery("corpid.keyword", formDataListDTO.getCorpid()));
            boolQueryBuilder1.filter(termsQuery("id", contractIdList));
            boolQueryBuilder1.filter(termQuery("del", 0));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_CONTRACT.getType()));
            sourceBuilder1.query(boolQueryBuilder1);
            SearchRequest searchRequest1 = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTRACT.getIndex());
            searchRequest1.source(sourceBuilder1);
            XbbAggregatedPage<PaasFormDataEntityExt> esContractEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest1, PaasFormDataEntityExt.class);
            // 关联合同列表
            List<PaasFormDataEntityExt> contractList = esContractEntities.getContent();
            for (PaasFormDataEntityExt paasFormDataEntityExt : contractList) {
                JSONObject data = paasFormDataEntityExt.getData();
                if (data == null) {
                    continue;
                }
                Double amount = data.getDouble(ContractEnum.AMOUNT.getAttr());
                contractAmountMap.put(paasFormDataEntityExt.getDataId(), amount);
            }
            List<Long> invoiceIdRefContract = new ArrayList<>();
            param.remove("invoiceIdIn");
            param.put("contractIdIn",contractIdList);
            List<InvoiceRelationshipEntity> invoiceRelationshipEntityList = invoiceRelationshipModel.getByParam(param);
            invoiceRelationshipEntityList.forEach(item ->{
                invoiceIdRefContract.add(item.getInvoiceId());
            });
            //红冲部分的金额
            Map<Long, Double> contractRedInvoiceMap = invoiceService.getRedTotalMoneyByIdIn(invoiceIdRefContract,null,formDataListDTO.getCorpid());
            Map<Long,Double> contractRealInvoiceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            invoiceRelationshipEntityList.forEach(item ->{
                double invoiceAmount = item.getMoney();
                contractRealInvoiceMap.merge(item.getContractId(),invoiceAmount,(a, b) -> a + b);
            });
            Iterator<Map.Entry<Long,Double>> iterator = contractRealInvoiceMap.entrySet().iterator();
            while(iterator.hasNext()){
                Map.Entry<Long,Double> entry = iterator.next();
                Long key = entry.getKey();
                if(contractRedInvoiceMap.containsKey(key)){
                    double realInvoice = contractRealInvoiceMap.getOrDefault(key,0D) + contractRedInvoiceMap.getOrDefault(key,0D);
                    contractRealInvoiceMap.put(key,realInvoice);
                }
            }
            Iterator<Map.Entry<Long,Double>> contractIterator = contractAmountMap.entrySet().iterator();
            while(contractIterator.hasNext()){
                Map.Entry<Long,Double> entry = contractIterator.next();
                Long key = entry.getKey();
                Double amount = entry.getValue();
                if(Objects.isNull(amount)){
                    amount = 0D;
                }
                double contractUnInvoiceAmount = amount - contractRealInvoiceMap.getOrDefault(key,0D);
                contractLeftInvoiceMap.put(key,contractUnInvoiceAmount);
            }
        }
        listOptionPackagePojo.setContractLeftInvoiceAmountMap(contractLeftInvoiceMap);
        Map<Long,Double> refRealInvoiceResultMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //父子回款单情况下将子回款单的信息组装到父中
        if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT_SHEET)) {
            for (Long parentId : parentIds) {
                Set<Long> childPaymentSheetIds = parentIdToChildPaymentSheetIds.get(parentId);
                for (Map.Entry<Long, Double> entry : refRealInvoiceMap.entrySet()) {
                    Long id = entry.getKey();
                    Double amount = entry.getValue();
                    if (childPaymentSheetIds != null && childPaymentSheetIds.contains(id)) {
                        refRealInvoiceResultMap.merge(parentId, amount, Double::sum);
                    } else {
                        refRealInvoiceResultMap.put(id, amount);
                    }
                }
            }
        } else {
            refRealInvoiceResultMap = refRealInvoiceMap;
        }
        listOptionPackagePojo.setPaymentIdInvoiceAmountMap(refRealInvoiceResultMap);
    }

    private void disabledButton(ListOptionPackagePojo listOptionPackagePojo, Integer businessType, PaasFormDataEntityExt entity, Set<String> permSet, Long currentModelType) throws XbbException{
        if (Objects.equals(businessType,XbbRefTypeEnum.INVOICE.getCode()) || Objects.equals(businessType,XbbRefTypeEnum.PURCHASE_INVOICE.getCode())){
            String redAttr = null;
            String hasRedAttr = null;
            String cancelAttr = null;
            String optionRedTab = null;
            String optionCancelTab = null;
            String invoiceRedPerStr = null;
            String invoiceCancelPerStr = null;
            String totalMoneyStr = null;
            if(Objects.equals(businessType,XbbRefTypeEnum.INVOICE.getCode())){
                redAttr = InvoiceEnum.IS_RED.getAttr();
                hasRedAttr = InvoiceEnum.HAS_RED.getAttr();
                cancelAttr = InvoiceEnum.IS_CANCEL.getAttr();
                optionRedTab = ListOptionTabEnum.RED.getAttr();
                optionCancelTab = ListOptionTabEnum.CANCEL.getAttr();
                invoiceRedPerStr = ProPermissionAliasEnum.INVOICE_RED.getAlias();
                invoiceCancelPerStr = ProPermissionAliasEnum.INVOICE_CANCEL.getAlias();
                totalMoneyStr = InvoiceEnum.TOTAL_MONEY.getAttr();
            }else {
                redAttr = PurchaseInvoiceEnum.IS_RED.getAttr();
                hasRedAttr = PurchaseInvoiceEnum.HAS_RED.getAttr();
                cancelAttr = PurchaseInvoiceEnum.IS_CANCEL.getAttr();
                optionRedTab = ListOptionTabEnum.PURCHASE_INVOICE_RED.getAttr();
                optionCancelTab = ListOptionTabEnum.PURCHASE_INVOICE_CANCEL.getAttr();
                invoiceRedPerStr = ProPermissionAliasEnum.PURCHASE_INVOICE_RED.getAlias();
                invoiceCancelPerStr = ProPermissionAliasEnum.PURCHASE_INVOICE_CANCEL.getAlias();
                totalMoneyStr = PurchaseInvoiceEnum.TOTAL_MONEY.getAttr();
            }
            if(Objects.equals(entity.getData().getInteger(redAttr),BasicConstant.ONE)){
                for (ButtonPojo buttonPojo : listOptionPackagePojo.getOptionList()) {
                    buttonPojo.setDisabled(BasicConstant.ONE);
                }
            }else {
                for (ButtonPojo buttonPojo : listOptionPackagePojo.getOptionList()) {
                    if (Objects.equals(optionRedTab, buttonPojo.getAttr())) {
                        Map<Long, Double> redTotalMoneyByIdMap = listOptionPackagePojo.getRedTotalMoneyByIdMap();
                        buttonPojo.setDisabled(permSet.contains(invoiceRedPerStr) && Objects.equals(entity.getData().getInteger(hasRedAttr), 1) && -redTotalMoneyByIdMap.getOrDefault(entity.getId(), 0D) >= entity.getData().getDouble(totalMoneyStr) ? 1 : 0);
                        if(Objects.equals(entity.getData().getInteger(cancelAttr),BasicConstant.ONE)){
                            buttonPojo.setDisabled(BasicConstant.ONE);
                        }
                    } else if (Objects.equals(optionCancelTab, buttonPojo.getAttr())) {
                        buttonPojo.setDisabled((permSet.contains(invoiceCancelPerStr) && Objects.equals(entity.getData().getInteger(cancelAttr), 1) || Objects.equals(entity.getData().getInteger(hasRedAttr), 1)) ? 1 : 0);
                    }
                }
            }
        }else if (Objects.equals(businessType,XbbRefTypeEnum.PAYMENT.getCode())){
            for (ButtonPojo buttonPojo : listOptionPackagePojo.getOptionList()){
                if (Objects.equals(ListOptionTabEnum.ADDPAYMENT.getAttr(),buttonPojo.getAttr())) {
                    //新加需要判断同时有回款单的新增权限
                    buttonPojo.setDisabled(PaymentStatusEnum.addPermission(entity.getData().getString(PaymentEnum.STATUS.getAttr())) && permSet.contains(ProPermissionAliasEnum.PAYMENT_SHEET_ADD.getAlias()) ? 0 : 1);
                }else if (Objects.equals(ListOptionTabEnum.PAYMENT_WRITE_OFF.getAttr(),buttonPojo.getAttr())){
                    //未收、部分未收才有核销按钮
                    boolean flag = PaymentStatusEnum.addPermission(entity.getData().getString(PaymentEnum.STATUS.getAttr())) && permSet.contains(ProPermissionAliasEnum.PAYMENT_WRITE_OFF.getAlias());
                    //新加需要判断同时有回款单的新增权限
                    buttonPojo.setDisabled(flag ? 0 : 1);
                }else if (Objects.equals(ListOptionTabEnum.ADDINVOICE.getAttr(),buttonPojo.getAttr())){
                    //处理新建发票按钮显示or隐藏
                    dealAddInvoice(currentModelType, listOptionPackagePojo, permSet, buttonPojo, entity, XbbRefTypeEnum.PAYMENT);
                }
            }
        }else if (Objects.equals(businessType,XbbRefTypeEnum.PAY_PLAN.getCode())){
            for (ButtonPojo buttonPojo : listOptionPackagePojo.getOptionList()){
                if (Objects.equals(ListOptionTabEnum.ADDPAYPLAN.getAttr(),buttonPojo.getAttr())){
                    buttonPojo.setDisabled(PayPlanStatusEnum.addPermission(entity.getData().getString(PayPlanEnum.STATUS.getAttr())) && permSet.contains(ProPermissionAliasEnum.PAY_SHEET_ADD.getAlias()) ? 0 : 1);
                }else if(Objects.equals(ListOptionTabEnum.ADDPURCHASEINVOICE.getAttr(),buttonPojo.getAttr())){
                    checkCanInvoice(listOptionPackagePojo,permSet,buttonPojo,entity,XbbRefTypeEnum.PAY_PLAN);
                }
            }
        } else if (Objects.equals(businessType,XbbRefTypeEnum.PAYMENT_SHEET.getCode())) {
            JSONObject data = entity.getData();
            String type = data.getString(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr());
            //可以新建发票的回款单类型
            boolean canNewInvoice = SheetTypeEnum.ifNewInvoice(type);
            for (ButtonPojo buttonPojo : listOptionPackagePojo.getOptionList()) {
                if (Objects.equals(ListOptionTabEnum.ADDINVOICE.getAttr(),buttonPojo.getAttr())){
                    if (!canNewInvoice) {
                        //不能新建发票
                        buttonPojo.setDisabled(BasicConstant.ONE);
                    } else {
                        //处理新建发票按钮显示or隐藏
                        dealAddInvoice(currentModelType, listOptionPackagePojo, permSet, buttonPojo, entity, XbbRefTypeEnum.PAYMENT_SHEET);
                    }
                }
            }
        } else if (Objects.equals(businessType,XbbRefTypeEnum.PAY_SHEET.getCode())) {
            for (ButtonPojo buttonPojo : listOptionPackagePojo.getOptionList()) {
                JSONObject data = entity.getData();
                String type = data.getString(PaySheetEnum.PAY_SHEET_TYPE.getAttr());
                buttonPojo.setDisabled(SheetTypeEnum.ifNewInvoice(type)? 0 : 1);
                checkCanInvoice(listOptionPackagePojo,permSet,buttonPojo,entity,XbbRefTypeEnum.PAY_SHEET);
            }
        }
    }

    /**
     * 处理应收款、回款单新建发票按钮：置灰or显示
     * @param currentModelType
     * @param listOptionPackagePojo
     * @param permSet
     * @param buttonPojo
     * @param entity
     * @param xbbRefTypeEnum
     * @throws XbbException
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private void dealAddInvoice(Long currentModelType, ListOptionPackagePojo listOptionPackagePojo, Set<String> permSet, ButtonPojo buttonPojo, PaasFormDataEntityExt entity, XbbRefTypeEnum xbbRefTypeEnum) throws XbbException {
        //当前数据应收款生成时的模式
        Long modelType = entity.getSysLong10();
        /**
         有三种情况下新建发票按钮需要隐藏或者置灰
         （1）“手动创建应收”模式下产生的应收款/回款单，在开票模式下新建发票，隐藏
         （2）开票模式下生成的应收款/回款单，“手动创建应收”模式下新建发票，置灰
         （3）开票模式下生成的应收款/回款单，开票模式下新建发票，隐藏
         总结：开票模式时，隐藏新建发票按钮（隐藏操作：setOptionBase方法已处理，开票模式时未塞入新建发票按钮）；开票模式生成的数据，在其他模式时（非开票模式），新建发票按钮【置灰】
         */
        //开票模式生成的数据，在其他模式时（非开票模式），新建发票按钮【置灰】
        boolean flag = Objects.equals(modelType, ModelTypeEnum.INVOICE.getCode()) && !Objects.equals(currentModelType, ModelTypeEnum.INVOICE.getCode());
        if (flag) {
            buttonPojo.setDisabled(BasicConstant.ONE);
        } else {
            buttonPojo.setDisabled(BasicConstant.ZERO);
            checkCanInvoice(listOptionPackagePojo, permSet, buttonPojo, entity, xbbRefTypeEnum);
        }
    }

    private void checkCanInvoice(ListOptionPackagePojo listOptionPackagePojo,Set<String> permSet,ButtonPojo buttonPojo,PaasFormDataEntityExt entity,XbbRefTypeEnum xbbRefTypeEnum) throws XbbException{
        Map<Long,Double> paymentIdAmountMap = listOptionPackagePojo.getPaymentIdInvoiceAmountMap() == null ? new HashMap<>() : listOptionPackagePojo.getPaymentIdInvoiceAmountMap();
        Map<Long,Double> contractLeftInvoiceAmountMap = listOptionPackagePojo.getContractLeftInvoiceAmountMap();
        JSONObject data = entity.getData();
        boolean invoicePermission = false;
        boolean isPrePaymentSheet = false;
        double refAmount = 0D;
        if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAYMENT)){
            invoicePermission = permSet.contains(ProPermissionAliasEnum.INVOICE_ADD.getAlias()) && PaymentStatusEnum.invoicePermission(data.getString(PaymentEnum.STATUS.getAttr()));
            refAmount = data.getDouble(PaymentEnum.AMOUNT.getAttr()) == null ? 0d : data.getDouble(PaymentEnum.AMOUNT.getAttr());
        }else if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAYMENT_SHEET)){
            invoicePermission = permSet.contains(ProPermissionAliasEnum.INVOICE_ADD.getAlias()) && SheetTypeEnum.ifNewInvoice(data.getString(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr()));
            String paymentSheetType = FastJsonHelper.getStringOrDefaultFromFormData(data,PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(),PaymentSheetTypeEnum.WRITE_OFF.getCode());
            isPrePaymentSheet = Objects.equals(paymentSheetType,PaymentSheetTypeEnum.PREPAYMENT.getCode());
            refAmount = data.getDouble(PaymentSheetEnum.AMOUNT.getAttr()) == null ? 0d : data.getDouble(PaymentSheetEnum.AMOUNT.getAttr());
        }else if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_PLAN)){
            invoicePermission = permSet.contains(ProPermissionAliasEnum.PURCHASE_INVOICE_ADD.getAlias()) && PayPlanStatusEnum.invoicePermission(data.getString(PayPlanEnum.STATUS.getAttr()));
            refAmount = data.getDouble(PayPlanEnum.AMOUNT.getAttr()) == null ? 0d : data.getDouble(PayPlanEnum.AMOUNT.getAttr());
        }else if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAY_SHEET)) {
            invoicePermission = permSet.contains(ProPermissionAliasEnum.PURCHASE_INVOICE_ADD.getAlias()) && SheetTypeEnum.ifNewInvoice(data.getString(PaySheetEnum.PAY_SHEET_TYPE.getAttr()));
            String paySheetType = FastJsonHelper.getStringOrDefaultFromFormData(data, PaySheetEnum.PAY_SHEET_TYPE.getAttr(), PaySheetTypeEnum.WRITE_OFF_PAY.getCode());
            isPrePaymentSheet = Objects.equals(paySheetType, PaySheetTypeEnum.PREPAY.getCode());
            refAmount = data.getDouble(PaySheetEnum.AMOUNT.getAttr()) == null ? 0d : data.getDouble(PaySheetEnum.AMOUNT.getAttr());
        }
        buttonPojo.setDisabled(invoicePermission ? 0 : 1);
        if (!invoicePermission) {
            // 已经判断为没权限的，不走下面逻辑
            return;
        }
        if(!isPrePaymentSheet) {
            if (contractLeftInvoiceAmountMap == null || contractLeftInvoiceAmountMap.isEmpty()) {
                // 无关联合同开票记录，可以开票
                buttonPojo.setDisabled(0);
            }
        }

        Double contractLeftInvoiceAmount = 0D;
        // 可以开票时，再判断回款已开票金额
        Double invoiceAmount = paymentIdAmountMap.get(entity.getId()) == null ? 0D : paymentIdAmountMap.get(entity.getId());
        buttonPojo.setDisabled(refAmount - invoiceAmount > 0 ? 0 : 1);
        boolean hasUnInvoiceOver = false;
        if(refAmount - invoiceAmount >0){
            hasUnInvoiceOver = true;
        }
        if(!isPrePaymentSheet) {
            if (Objects.nonNull(contractLeftInvoiceAmountMap)) {
                if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT)) {
                    contractLeftInvoiceAmount = contractLeftInvoiceAmountMap.get(data.getLong(PaymentEnum.CONTRACT.getAttr()));
                    // 合同剩余可开票金额小于0，不可以开票 预收款回款单没有合同
                    if (contractLeftInvoiceAmount != null && contractLeftInvoiceAmount <= 0) {
                        buttonPojo.setDisabled(1);
                    }
                } else if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT_SHEET)) {
                    JSONArray contractArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, PaymentSheetEnum.CONTRACT.getAttr(), new JSONArray());
                    if (CollectionsUtil.isNotEmpty(contractArray)) {
                        boolean hasContractOrPurchaseUnInvoiceOver = false;
                        for(int i=0;i<contractArray.size();i++){
                            Long contractId = contractArray.getLong(i);
                            contractLeftInvoiceAmount = contractLeftInvoiceAmountMap.get(contractId);
                            if (contractLeftInvoiceAmount != null && contractLeftInvoiceAmount <= 0) {
                                buttonPojo.setDisabled(1);
                            }else {
                                //回款单没有开完,合同还有
                                hasContractOrPurchaseUnInvoiceOver = true;
                            }
                        }
                        if(hasUnInvoiceOver && hasContractOrPurchaseUnInvoiceOver){
                            buttonPojo.setDisabled(0);
                        }
                    }
                }else if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_PLAN)){
                    contractLeftInvoiceAmount = contractLeftInvoiceAmountMap.get(data.getLong(PayPlanEnum.LINK_PURCHASE.getAttr()));
                    // 合同剩余可开票金额小于0，不可以开票 预收款回款单没有合同
                    if (contractLeftInvoiceAmount != null && contractLeftInvoiceAmount <= 0) {
                        buttonPojo.setDisabled(1);
                    }
                }else if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAY_SHEET)) {
                    JSONArray contractArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, PaySheetEnum.LINK_PURCHASE.getAttr(), new JSONArray());
                    if (CollectionsUtil.isNotEmpty(contractArray)) {
                        boolean hasContractOrPurchaseUnInvoiceOver = false;
                        for(int i=0;i<contractArray.size();i++){
                            Long contractId = contractArray.getLong(i);
                            contractLeftInvoiceAmount = contractLeftInvoiceAmountMap.get(contractId);
                            if (contractLeftInvoiceAmount != null && contractLeftInvoiceAmount <= 0) {
                                buttonPojo.setDisabled(1);
                            }else {
                                //付款单没有开完,合同还有
                                hasContractOrPurchaseUnInvoiceOver = true;
                            }
                        }
                        if(hasUnInvoiceOver && hasContractOrPurchaseUnInvoiceOver){
                            buttonPojo.setDisabled(0);
                        }
                    }
                }
            }
        }
    }

    public void setOption(WorkOrderDataEsListVO workOrderDataEsListVO, FormDataListDTO formDataListDTO) throws XbbException {
        // 获取参数
        String corpid = formDataListDTO.getCorpid();
        Integer businessType = formDataListDTO.getBusinessType();
        Integer subBusinessType = formDataListDTO.getSubBusinessType();
        Long listGroupId = formDataListDTO.getListGroupId();

        List<WorkOrderEntityExt> list = workOrderDataEsListVO.getPaasFormDataESList();
//        if (list == null || list.isEmpty()){
//            return;
//        }
        List<Long> dataIdList = new ArrayList<>();
        for (WorkOrderEntityExt entity : list) {
            dataIdList.add(entity.getId());
        }
        dataIdList.add(-1L);
        for (FieldAttrEntity fieldAttrEntity : workOrderDataEsListVO.getHeadList()) {
            if (Objects.equals(fieldAttrEntity.getAttr(), WorkOrderEnum.SHEET_NO.getAttr())) {
                fieldAttrEntity.setTagAttr(WorkOrderEnum.SHEET_NO.getAttr() + "Tag");
                break;
            }
        }
        ListOptionPackagePojo listOptionPackagePojo = setOptionBase(dataIdList, formDataListDTO);

        List<FieldAttrEntity> headList = workOrderDataEsListVO.getHeadList();
        setHeadList(headList, listOptionPackagePojo, subBusinessType, businessType);
//        String attr = RowNameEnum.WORKORDER.getAttr();
        for (FieldAttrEntity fieldAttrEntity : headList){
            if (Objects.equals(fieldAttrEntity.getFieldType(),FieldTypeEnum.LINK_BUSINESS_SINGLE.getType())
                    || Objects.equals(fieldAttrEntity.getFieldType(),FieldTypeEnum.LINK_BUSINESS_MULTI.getType())) {
                LinkDetailPojo linkDetail = new LinkDetailPojo();
                linkDetail.setBusinessType(fieldAttrEntity.getLinkedType());
                linkDetail.setSubBuisenssType(fieldAttrEntity.getLinkedType());
                linkDetail.setSaasMark(SaasMarkEnum.SAAS.getCode());
                fieldAttrEntity.setLinkDetail(linkDetail);
            }
        }

        RelativeProductExplainVO relativeProductExplainVO = saasAddHelp.getRelativeProductExplainsFromDB(corpid, subBusinessType, listGroupId);
        for (WorkOrderEntityExt entity : list){
            setOptionValue(entity,formDataListDTO, listOptionPackagePojo, businessType, subBusinessType, listGroupId, null, relativeProductExplainVO);
        }
    }
    public void setOption(PrePaymentBalanceListVO prePaymentBalanceListVO, FormDataListDTO formDataListDTO) throws XbbException {
        // 获取参数
        String corpid = formDataListDTO.getCorpid();
        Integer businessType = formDataListDTO.getBusinessType();
        Integer subBusinessType = formDataListDTO.getSubBusinessType();
        Long listGroupId = formDataListDTO.getListGroupId();

        // TODO 不知道为什么，兼容代码
        RelativeProductExplainVO relativeProductExplainVO = saasAddHelp.getRelativeProductExplainsFromDB(corpid, subBusinessType, formDataListDTO.getListGroupId());

        List<PaymentBalanceEntity> list = prePaymentBalanceListVO.getPaasFormDataESList();
        ListOptionPackagePojo listOptionPackagePojo = new ListOptionPackagePojo();
        ListOptionPackagePojo oneListOptionPackagePojo = new ListOptionPackagePojo();
        List<ButtonPojo> oneOptionList  = oneListOptionPackagePojo.getOptionList();
        List<ButtonPojo> optionList = listOptionPackagePojo.getOptionList();
        //查看按钮
        ButtonPojo buttonPojo1 = new ButtonPojo(ListOptionTabEnum.OPTION_WRITE_OFF_PREPAYMENT, XbbRefTypeEnum.WRITE_OFF_PREPAYMENT.getCode(), formDataListDTO.getDistributorMark());
        buttonPojo1.setLinkBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        optionList.add(buttonPojo1);
        ButtonPojo view = new ButtonPojo(ListOptionTabEnum.VIEW, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), formDataListDTO.getDistributorMark());
        optionList.add(view);
        ButtonPojo buttonPojo = new ButtonPojo(ListOptionTabEnum.OPTION_WRITE_OFF_PREPAYMENT, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), formDataListDTO.getDistributorMark());
        buttonPojo.setDisabled(1);
        oneOptionList.add(buttonPojo);
        oneOptionList.add(view);
        List<FieldAttrEntity> headList = prePaymentBalanceListVO.getHeadList();
        setHeadList(headList,listOptionPackagePojo, subBusinessType, businessType);
        for (FieldAttrEntity fieldAttrEntity : headList){
            if (Objects.equals(fieldAttrEntity.getFieldType(),FieldTypeEnum.LINK_BUSINESS_SINGLE.getType())
                    || Objects.equals(fieldAttrEntity.getFieldType(),FieldTypeEnum.LINK_BUSINESS_MULTI.getType())) {
                LinkDetailPojo linkDetail = new LinkDetailPojo();
                linkDetail.setBusinessType(fieldAttrEntity.getLinkedType());
                linkDetail.setSubBuisenssType(fieldAttrEntity.getLinkedType());
                linkDetail.setSaasMark(SaasMarkEnum.SAAS.getCode());
                fieldAttrEntity.setLinkDetail(linkDetail);
            }
        }

        UserVO loginUser = formDataListDTO.getLoginUser();
        Set<String> permSet = loginUser.getPermSet();
        boolean writeOffB = false;
        //核销
        if (permSet.contains(ProPermissionAliasEnum.PAYMENT_SHEET_ADD.getAlias()) && !Objects.equals(ProPermissionAliasEnum.PAYMENT_SHEET_ADD.getAlias(), StringConstant.POSITIVE_NUMBER)) {
            writeOffB = true;
        }
        for (PaymentBalanceEntity entity : list){
            JSONObject data = entity.getData();
            Double advancePaymentBalance = entity.getAdvancePaymentBalance();
            Integer contractCount = entity.getContractCount();
            boolean contractCountB = contractCount != null && contractCount > 0;
            boolean advanceB = advancePaymentBalance != null && advancePaymentBalance > 0;
            //只有当预收款余额>0，切待核销合同个数大于0才可以核销
            if(contractCountB && advanceB && writeOffB){
                setOptionValue(entity,formDataListDTO, listOptionPackagePojo, businessType, subBusinessType, listGroupId, null, relativeProductExplainVO);
            }else{
                setOptionValue(entity, formDataListDTO,oneListOptionPackagePojo, businessType, subBusinessType, listGroupId, null, relativeProductExplainVO);
            }
            entity.setData(data);
        }
    }

    public void setPrePayBalanceOption(PrePayBalanceListVO prePayBalanceListVO, FormDataListDTO formDataListDTO) throws XbbException {
        // 获取参数
        Integer businessType = formDataListDTO.getBusinessType();
        Integer subBusinessType = formDataListDTO.getSubBusinessType();
        Long listGroupId = formDataListDTO.getListGroupId();

        RelativeProductExplainVO relativeProductExplainVO = saasAddHelp.getRelativeProductExplainsFromDB(formDataListDTO.getCorpid(), subBusinessType, formDataListDTO.getListGroupId());

        List<PayBalanceEntity> list = prePayBalanceListVO.getPaasFormDataESList();
//        if (list == null || list.isEmpty()){
//            return;
//        }
/*        List<Long> dataIdList = new ArrayList<>();
        for (PaymentBalanceEntity entity : list) {
            dataIdList.add(entity.getId());
        }
        dataIdList.add(-1L);*/
        ListOptionPackagePojo listOptionPackagePojo = new ListOptionPackagePojo();
        ListOptionPackagePojo oneListOptionPackagePojo = new ListOptionPackagePojo();
        List<ButtonPojo> oneOptionList  = oneListOptionPackagePojo.getOptionList();
        List<ButtonPojo> optionList = listOptionPackagePojo.getOptionList();
        //查看按钮
        ButtonPojo buttonPojo1 = new ButtonPojo(ListOptionTabEnum.OPTION_WRITE_OFF_PREPAY, XbbRefTypeEnum.WRITE_OFF_PREPAY.getCode());
        buttonPojo1.setLinkBusinessType(XbbRefTypeEnum.SUPPLIER.getCode());
        optionList.add(buttonPojo1);
        ButtonPojo view = new ButtonPojo(ListOptionTabEnum.VIEW, XbbRefTypeEnum.SUPPLIER.getCode());
        optionList.add(view);
        ButtonPojo buttonPojo = new ButtonPojo(ListOptionTabEnum.OPTION_WRITE_OFF_PREPAY, XbbRefTypeEnum.SUPPLIER.getCode());
        buttonPojo.setDisabled(1);
        oneOptionList.add(buttonPojo);
        oneOptionList.add(view);
//        ListOptionPackagePojo listOptionPackagePojo = setOptionBase(dataIdList, formDataListDTO);
        List<FieldAttrEntity> headList = prePayBalanceListVO.getHeadList();
        setHeadList(headList,listOptionPackagePojo, subBusinessType,businessType);
//        String attr = RowNameEnum.WORKORDER.getAttr();
        for (FieldAttrEntity fieldAttrEntity : headList){
            if (Objects.equals(fieldAttrEntity.getFieldType(),FieldTypeEnum.LINK_BUSINESS_SINGLE.getType())
                    || Objects.equals(fieldAttrEntity.getFieldType(),FieldTypeEnum.LINK_BUSINESS_MULTI.getType())) {
                LinkDetailPojo linkDetail = new LinkDetailPojo();
                linkDetail.setBusinessType(fieldAttrEntity.getLinkedType());
                linkDetail.setSubBuisenssType(fieldAttrEntity.getLinkedType());
                linkDetail.setSaasMark(SaasMarkEnum.SAAS.getCode());
                fieldAttrEntity.setLinkDetail(linkDetail);
            }
        }

        UserVO loginUser = formDataListDTO.getLoginUser();
        Set<String> permSet = loginUser.getPermSet();
        boolean writeOffB = false;
        //核销
        if (permSet.contains(ProPermissionAliasEnum.PAY_SHEET_ADD.getAlias()) && !Objects.equals(ProPermissionAliasEnum.PAY_SHEET_ADD.getAlias(), StringConstant.POSITIVE_NUMBER)) {
            writeOffB = true;
        }
        for (PayBalanceEntity entity : list){
            JSONObject data = entity.getData();
            Double advancePaymentBalance = entity.getAdvancePayBalance();
            Integer contractCount = entity.getPurchaseCount();
            boolean contractCountB = contractCount != null && contractCount > 0;
            boolean advanceB = advancePaymentBalance != null && advancePaymentBalance > 0;
            //只有当预收款余额>0，切待核销合同个数大于0才可以核销
            if(contractCountB && advanceB && writeOffB){
                setOptionValue(entity, formDataListDTO,listOptionPackagePojo, businessType, subBusinessType, listGroupId, null, relativeProductExplainVO);
            }else{
                setOptionValue(entity, formDataListDTO,oneListOptionPackagePojo, businessType, subBusinessType, listGroupId, null, relativeProductExplainVO);
            }
            entity.setData(data);
        }
    }

    /**
     * 设置特殊操作栏
     *
     * @param entity                数据实体
     * @param listOptionPackagePojo 标签封装信息
     * @param businessType          业务类型
     * @param subBusinessType       子业务类型
     * @param listGroupId           分组id(库存)
     * @throws XbbException
     */
    public void setOptionValue(PaasFormDataEntityExt entity,FormDataListDTO formDataListDTO, ListOptionPackagePojo listOptionPackagePojo, Integer businessType, Integer subBusinessType, Long listGroupId, Map<String, FieldAttrEntity> explainMap, RelativeProductExplainVO relativeProductExplainVO) throws XbbException {
        String userId = formDataListDTO.getUserId();
        Long dataId = entity.getDataId();
        JSONObject data = entity.getData();
        data = data == null ? new JSONObject() : data;
        JSONObject tagData = entity.getTagData();
        String corpid = entity.getCorpid();
        if (listOptionPackagePojo.getNeedOption0()) {
            // 库存查询列表页没有操作按钮
            JSONObject option = new JSONObject();
            List<ButtonPojo> buttonPojoList = ButtonPojo.deepClone(listOptionPackagePojo.getOptionList());
            if (listOptionPackagePojo.getOnline()) {
//                List<ButtonPojo> tempOptionList = new ArrayList<>(listOptionPackagePojo.getOptionList());
                if (Objects.equals(businessType, XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode())) {
                    buttonPojoList.add(Objects.equals(data.getString(MarketingBaseEnum.STATUS.getAttr()), MarketingStatusEnum.ONLINE.getName()) ? new ButtonPojo(ListOptionTabEnum.OFFLINE) : new ButtonPojo(ListOptionTabEnum.ONLINE));
                }else {
                    buttonPojoList.add(Objects.equals(data.getInteger(ProductEnum.ONLINE.getAttr()), 1) ? new ButtonPojo(ListOptionTabEnum.OFFLINE) : new ButtonPojo(ListOptionTabEnum.ONLINE));
                }
                option.put("value", buttonPojoList);
            }else if (listOptionPackagePojo.getFinish()) {
                if (Objects.equals(businessType, XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode())) {
                    ButtonPojo buttonPojo = new ButtonPojo(ListOptionTabEnum.FINISH);
                    buttonPojo.setDisabled(1);
                    buttonPojoList.add(buttonPojo);
                }
                option.put("value", buttonPojoList);
            }  else if (listOptionPackagePojo.getProductionOrderFinish()) {
//                List<ButtonPojo> tempOptionList = new ArrayList<>(listOptionPackagePojo.getOptionList());
                buttonPojoList.add(Objects.equals(data.getInteger(ProductionOrderEnum.STATUS.getAttr()), 1) ? new ButtonPojo(ListOptionTabEnum.FINISH) : new ButtonPojo(ListOptionTabEnum.RESTART));
                option.put("value", buttonPojoList);
            } else if (Objects.equals(subBusinessType, XbbRefTypeEnum.SEQ_SEARCH.getCode())) {
                option.put("value", 1);
            } else if (listOptionPackagePojo.getFreeze()) {
                buttonPojoList.add(Objects.equals(data.getString(CreditLimitEnum.STATUS.getAttr()), CreditLimitStatusEnum.NORMAL.getCode()) ? new ButtonPojo(ListOptionTabEnum.CREDIT_FREEZE) : new ButtonPojo(ListOptionTabEnum.CREDIT_UNFREEZE));
                option.put("value", buttonPojoList);
            } else if (listOptionPackagePojo.getRevoke()) {
                // 产品说暂不做重新生效，没过期的临时额度都可撤销
                int endTime = data.getIntValue(CreditTemporaryLimitEnum.END_TIME.getAttr());
                String status = data.getString(CreditTemporaryLimitEnum.APPLY_STATUS.getAttr());
                ButtonPojo revokeBtn = new ButtonPojo(ListOptionTabEnum.CREDIT_REVOKE);
                if (endTime >= DateTimeUtil.getTodayInt() && Objects.equals(status, CreditTemporaryApplyStatusEnum.NORMAL.getCode())) {
                    buttonPojoList.add(revokeBtn);
                } else {
                    revokeBtn.setDisabled(1);
                    buttonPojoList.add(revokeBtn);
                }
                option.put("value", buttonPojoList);
            } else if (listOptionPackagePojo.getStatement()) {
                int statementArchive = data.getIntValue(CustomerStatementStatisticEnum.IS_ARCHIVED.getAttr());
                String statementStatus = data.getString(CustomerStatementStatisticDistributorEnum.STATUS.getAttr());
                if (Objects.equals(formDataListDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                    if (Objects.equals(statementArchive, ArchivedEnum.UN_ARCHIVED.getCode())) {
                        if (Objects.equals(CustomerStatementStatusEnum.UNCONFIRMED.getCode(), statementStatus)) {
                            buttonPojoList.add(new ButtonPojo(ListOptionTabEnum.REMIND_CONFIRM_STATEMENT));
                            buttonPojoList.add(new ButtonPojo(ListOptionTabEnum.VALET_CONFIRM_STATEMENT));
                        }
                        buttonPojoList.add(new ButtonPojo(ListOptionTabEnum.REGENERATE_STATEMENT));
                    }
                } else if (Objects.equals(statementArchive, ArchivedEnum.UN_ARCHIVED.getCode())) {
                    buttonPojoList.add(new ButtonPojo(ListOptionTabEnum.REGENERATE_STATEMENT));
                }
                option.put("value", buttonPojoList);
            } else {
                option.put("value", buttonPojoList);
            }
            data.put(ListOptionEnum.OPTION.getAttr(), option);
        }
        if (listOptionPackagePojo.getNeedOption1()) {
            JSONObject json = new JSONObject();
            json.put("value", listOptionPackagePojo.getFocusList().contains(dataId) ? 1 : 0);
            data.put(ListOptionEnum.FOCUS.getAttr(), json);
        }
        if (listOptionPackagePojo.getNeedOption2()) {
            JSONObject json = new JSONObject();
            json.put("value", listOptionPackagePojo.getPushNotifyList().contains(dataId) ? 1 : 0);
            json.put("businessType", XbbRefTypeEnum.PUSH_NOTIFY.getCode());
            data.put(ListOptionEnum.REMIND.getAttr(), json);
        }
        if (listOptionPackagePojo.getNeedOption3()) {
            // 判断是否有呼叫权限
            boolean isActiveCall = callCenterCommonService.isOpenCallAndAgent(corpid, userId);
            // 判断是否有阿里云呼叫中心权限
            boolean isActiveAliyunCall = callCenterCommonService.isActiveAliyunCall(corpid,userId).IsActiveAliyunAndHasRole();
            //协同团队
            Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            userTeamService.getUserIdMap(Collections.singletonList(dataId),corpid,businessType,false,mainUserMap,coUserMap);

            // 当前数据的创建人、负责人、协同人、当前操作人
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            handlerExplainDTO.setLoginUser(formDataListDTO.getLoginUser());
            handlerExplainDTO.setUserId(userId);
            handlerExplainDTO.setOwnerId(mainUserMap.get(dataId));
            handlerExplainDTO.setCoUserId(coUserMap.get(dataId));
            handlerExplainDTO.setCreatorId(entity.getCreatorId());
            JSONObject json = new JSONObject();
            int value = 0;
            JSONArray customerPhoneArray = FastJsonHelper.getJsonArrFromFormData(data, CustomerManagementEnum.PHONE.getAttr());
            int aliyunCallCenterValue = 0;
            if (customerPhoneArray != null && !customerPhoneArray.isEmpty()) {
                JSONObject item = customerPhoneArray.getJSONObject(0);
                String tel = item.getString(StringConstant.PHONE_TEL_ATTR);
                if (Objects.nonNull(tel) && !StringUtil.isEmpty(tel)) {
                    value = 1;
                    aliyunCallCenterValue = 1;
                }
            }
            if(!isActiveCall){
                value = 0;
            }
            //  为客户回收站 客户联系人 线索回收站 线索联系人 就不展示
            if(Objects.equals(subBusinessType, XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode())
                    || Objects.equals(subBusinessType, XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode())
                    || Objects.equals(subBusinessType, XbbRefTypeEnum.CLUE_PUBLIC.getCode())
                    || Objects.equals(subBusinessType, XbbRefTypeEnum.CLUE_RECYCLE.getCode())){
                value = 0;
            }
            List<DetaPhonePojo> detaPhonePojos = cusCallPhone(data, businessType, corpid, explainMap, handlerExplainDTO);
            json.put("value", value);
            json.put("dial",detaPhonePojos);
            if(!isActiveAliyunCall){
                aliyunCallCenterValue = 0;
            }
            json.put("aliyunCallCenterValue", aliyunCallCenterValue);
            json.put("aliyunCallCenterDial", detaPhonePojos);
            data.put(ListOptionEnum.CALL.getAttr(), json);

            // 客户电话设置不可见，拨号列应隐藏。
            boolean flag = false;
            if ( explainMap != null) {
                FieldAttrEntity fieldAttrEntity = explainMap.get(CustomerManagementEnum.PHONE.getAttr());
                SubFormPoJo subForm = fieldAttrEntity.getSubForm();
                List<? extends FieldAttrEntity> items = subForm.getItems();
                if(CollectionsUtil.isNotEmpty(items)){
                    for (FieldAttrEntity item : items) {
                        if(StringConstant.PHONE_TEL_ATTR.equals(item.getAttr())){
                            if (BasicConstant.ZERO.equals(item.getVisible())) {
                                flag = true;
                                break;
                            }
                        }
                    }
                }
                if (BasicConstant.ZERO.equals(fieldAttrEntity.getVisible())||flag) {
                    json.put("value", 0);
                    json.put("dial",detaPhonePojos);
                    json.put("aliyunCallCenterValue", 0);
                    json.put("aliyunCallCenterDial", detaPhonePojos);
                    data.put(ListOptionEnum.CALL.getAttr(), json);
                }

            }
            /*// 客户电话设置不可见，拨号列应隐藏。
            if ((Objects.equals(XbbRefTypeEnum.CLUE.getCode(), subBusinessType)
                ||Objects.equals(XbbRefTypeEnum.CLUE_PUBLIC.getCode(), subBusinessType)
                ||Objects.equals(XbbRefTypeEnum.CLUE_RECYCLE.getCode(), subBusinessType)
            )&& explainMap != null) {
                FieldAttrEntity fieldAttrEntity = explainMap.get(ClueEnum.PHONE.getAttr());
                if (BasicConstant.ZERO.equals(fieldAttrEntity.getVisible())) {
                    data.remove(ListOptionEnum.CALL.getAttr());
                }
            }*/
        }
        if (listOptionPackagePojo.getNeedOption4()) {
            JSONObject json = new JSONObject();
            json.put("value", listOptionPackagePojo.getCommunicateList().contains(dataId) ? 1 : 0);
            data.put(ListOptionEnum.FLOW.getAttr(), json);
        }
        if (listOptionPackagePojo.getNeedOption5() || listOptionPackagePojo.getNeedOption10()) {
            JSONObject json = new JSONObject();
            List<WaitContractProductPojo> waitContractProductPojoList = listOptionPackagePojo.getWaitProductPojoMap().getOrDefault(dataId, new ArrayList<>());
            json.put("tableData", waitContractProductPojoList);
            Double num = 0D;
            for (WaitContractProductPojo waitContractProductPojo : waitContractProductPojoList) {
                num += waitContractProductPojo.getProductNum();
            }
            // 小数精度
//            FieldAttrEntity fieldAttrEntity = listOptionPackagePojo.getNeedOptionFieldAttrEntity8();
//            Integer accuracy = fieldAttrEntity != null && fieldAttrEntity.getAccuracy() != null ? fieldAttrEntity.getAccuracy() : 2;
            ProductFieldPojo stockField = saasFormHelp.getProductFieldPojo(RedisPrefixConstant.PRODUCT_STOCK,ProductEnum.STOCK.getAttr(), corpid);
            Integer accuracy = stockField.getAccuracy();
            num = attrDecimalPrecisionHelper.setPrecision(num, accuracy);
            json.put("previewText", String.format(I18nMessageUtil.getMessage(SaasConstant.WAIT_OUT_OF_STOCK_PRODUCTS), waitContractProductPojoList.size(), num.toString()));
            json.put("tableHead", getTableHead(businessType, subBusinessType));
            json.put(StringConstant.BUSINESS_TYPE, listOptionPackagePojo.getNeedOption5() ? XbbRefTypeEnum.PURCHASE.getCode() : XbbRefTypeEnum.PRODUCTION_ORDER.getCode());
            data.put(listOptionPackagePojo.getNeedOption5() ? ListOptionEnum.WAIT_PURCHASE_CONTRACT.getAttr() : ListOptionEnum.WAIT_PRODUCE_CONTRACT.getAttr(), json);
        }
        if (listOptionPackagePojo.getNeedOption6() || listOptionPackagePojo.getNeedOption11()) {
            JSONObject json = new JSONObject();
            List<Long> contractIdList = listOptionPackagePojo.getProductAndContractIdMap().get(dataId);
            List<WaitContractPojo> waitContractPojoList = new ArrayList<>();
            contractIdList = Objects.isNull(contractIdList) ? new ArrayList<>() : contractIdList;
            for (Long contractId : contractIdList) {
                WaitContractPojo waitContractPojo = listOptionPackagePojo.getWaitContractPojoMap().get(contractId);
                if (waitContractPojo != null) {
                    waitContractPojoList.add(waitContractPojo);
                }
            }
            json.put("tableData", waitContractPojoList);
            json.put("previewText", String.format(I18nMessageUtil.getMessage(SaasConstant.OUT_OF_STOCK_CONTRACT), waitContractPojoList.size()));
            json.put("tableHead", getTableHead(businessType, subBusinessType));
            data.put(listOptionPackagePojo.getNeedOption6() ? ListOptionEnum.WAIT_PURCHASE_PRODUCT.getAttr() : ListOptionEnum.WAIT_PRODUCE_PRODUCT.getAttr(), json);
            data.put(ProductEnum.STOCK.getAttr(),listOptionPackagePojo.getLackStockMap().get(dataId));
        }
        if (listOptionPackagePojo.getNeedOption7()) {
            JSONObject json = new JSONObject();
            JSONArray value = listOptionPackagePojo.getProductMap().getOrDefault(dataId,new JSONArray());
            if(!value.isEmpty()){
                boolean beProductId = false;
                for(Object valObj : value){
                    if(((JSONObject) valObj).getLong("productId") != null){
                        beProductId = true;
                    }
                }
                if(beProductId){
                    value.sort(Comparator.comparing(obj -> ((JSONObject) obj).getLong("productId")));
                }
            }
            json.put("value", value);
            JSONArray tableHeadArray = packageOptionTableHead(userId,subBusinessType, listGroupId, relativeProductExplainVO);

            // 24310 Web设置产品库存字段不可见，保质期查询页展开明细库存数量应隐藏。
            if (Objects.equals(XbbRefTypeEnum.GUARANTEE_SEARCH.getCode(), businessType) && explainMap != null) {
                FieldAttrEntity fieldAttrEntity = explainMap.get(ProductEnum.STOCK.getAttr());
                if (BasicConstant.ZERO.equals(fieldAttrEntity.getVisible())) {
                    Iterator<Object> iterator = tableHeadArray.iterator();
                    while (iterator.hasNext()) {
                        Object object = iterator.next();
                        JSONObject jsonObject = (JSONObject) object;
                        if (SubOptionTableHeadEnum.PRODUCT_NUM.getProp().equals(jsonObject.get("prop"))) {
                            iterator.remove();
                        }
                    }
                }
            }

            try {
                if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(subBusinessType, XbbRefTypeEnum.PRODUCT.getCode())) {
                    // 只处理产品列表 不影响库存查询列表
                    for (int i = 0; i < tableHeadArray.size(); i++) {
                        JSONObject obj = tableHeadArray.getJSONObject(i);
                        if (Objects.equals(obj.getString("prop"), "cost")) {
                            obj.put("prop", "cost4Show");
                        }
                        if (Objects.equals(obj.getString("prop"), "price")) {
                            obj.put("prop", "price4Show");
                        }
                        if (Objects.equals(obj.getString("prop"), "stock")) {
                            obj.put("prop", "stock4Show");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            json.put("tableHead", tableHeadArray);
            if (Objects.equals(subBusinessType,XbbRefTypeEnum.PRODUCT.getCode())){
                Map<String, FieldAttrEntity> productExplainMap = listOptionPackagePojo.getProductExplainMap();
                FieldAttrEntity priceField = productExplainMap.get(ProductEnum.PRICE.getAttr());
                if (priceField != null) {
                    productListHelp.setParentPrice(data, value, priceField);
                }
                FieldAttrEntity costField = productExplainMap.get(ProductEnum.COST.getAttr());
                if (costField != null) {
                    productListHelp.setParentPrice(data, value, costField);
                }
                if (Objects.equals(data.getInteger(ProductEnum.SPECIFICATION.getAttr()),1)){
                    data.put(ListOptionEnum.MULTI_SPEC.getAttr(), json);
                    data.put(ProductEnum.SPECIFICATION.getAttr(), String.format(I18nMessageUtil.getMessage(StringConstant.SPEC_NUM_FORMAT), value.size()));
                } else {
                    json.put("value",new JSONArray());
                    data.put(ListOptionEnum.MULTI_SPEC.getAttr(), json);
                    if (value.size() > 0) {
                        data.put(ProductEnum.SPECIFICATION.getAttr(), ((JSONObject) value.get(0)).getString("specification"));
                        data.put(ProductEnum.BARCODE.getAttr(), ((JSONObject) value.get(0)).getString("barcode"));
                    } else {
                        data.put(ProductEnum.SPECIFICATION.getAttr(), "");
                        data.put(ProductEnum.BARCODE.getAttr(), "");
                    }
                }
                double totalStock = 0D;
                for (int i=0; i<value.size(); i++) {
                    JSONObject childObj = value.getJSONObject(i);
                    double childStock = childObj.getDoubleValue("stock");
                    totalStock = Arith.add(totalStock, childStock);
                }
                data.put(ProductEnum.STOCK.getAttr(), totalStock);
            } else if (Objects.equals(subBusinessType,XbbRefTypeEnum.STOCK_SEARCH.getCode())) {
                double totalStock = 0D;
                double totalCost = 0D;
                boolean isHideCost = false;
                boolean isHideStock = false;
                for (int i=0; i<value.size(); i++) {
                    JSONObject childObj = value.getJSONObject(i);
                    double childStock = 0D;
                    if (Objects.equals(childObj.getString("stock"), BasicConstant.NULL_SHOW_STR)) {
                        isHideCost = true;
                        isHideStock = true;
                    } else {
                        childStock = childObj.getDoubleValue("stock");
                        totalStock = Arith.add(totalStock, childStock);
                    }
                    if (Objects.equals(childObj.getString("cost"), BasicConstant.NULL_SHOW_STR)) {
                        isHideCost = true;
                    } else {
                        double childCost = childObj.getDoubleValue("cost");
                        if (Objects.equals(childStock, 0D)) {
                            childObj.put("cost", BasicConstant.NULL_SHOW_STR);
                            childObj.put("costTotal", BasicConstant.NULL_SHOW_STR);
                        }
                        totalCost = Arith.add(totalCost, Arith.mul(childStock, childCost));
                    }
                }
                if (isHideStock) {
                    data.put(ProductEnum.STOCK.getAttr(), BasicConstant.NULL_SHOW_STR);
                } else {
                    data.put(ProductEnum.STOCK.getAttr(), totalStock);
                }
                if (isHideCost || Objects.equals(totalStock, 0D)) {
                    data.put("totalCost", BasicConstant.NULL_SHOW_STR);
                    data.put(ProductEnum.COST.getAttr(), BasicConstant.NULL_SHOW_STR);
                } else {
                    data.put("totalCost", totalCost);
                }
                data.put(ListOptionEnum.MULTI_SPEC.getAttr(), json);
            } else if (Objects.equals(subBusinessType,XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())){
                try {
                    double totalStock = 0D;
                    for (int i = 0; i < value.size(); i++) {
                        JSONObject childObj = value.getJSONObject(i);
                        double childStock = childObj.getDoubleValue("stock");
                        totalStock = Arith.add(totalStock, childStock);
                    }
                    data.put(ProductEnum.STOCK.getAttr(), totalStock);
                    data.put(ListOptionEnum.MULTI_SPEC.getAttr(), json);
                } catch (NumberFormatException numberFormatException) {
                    data.put(ProductEnum.STOCK.getAttr(), BasicConstant.NULL_SHOW_STR);
                    for (int i = 0; i < value.size(); i++) {
                        JSONObject childObj = value.getJSONObject(i);
                        childObj.put("num",  BasicConstant.NULL_SHOW_STR);
                    }
                    data.put(ListOptionEnum.MULTI_SPEC.getAttr(), json);
                }
            }else {
                data.put(ListOptionEnum.MULTI_SPEC.getAttr(), json);
            }
        }
        if (listOptionPackagePojo.getNeedOption8() || listOptionPackagePojo.getNeedOption9()) {
            if (Objects.equals(businessType,XbbRefTypeEnum.PURCHASE.getCode()) ||Objects.equals(businessType,XbbRefTypeEnum.CONTRACT.getCode()) ){
                JSONObject json = new JSONObject();
                List<WaitOutstockProductPojo> waitOutstockProductPojoList = listOptionPackagePojo.getWaitOutstockProductMap().getOrDefault(dataId, new ArrayList<>());
                Double num = 0D;
                for (WaitOutstockProductPojo waitOutstockProductPojo : waitOutstockProductPojoList) {
                    num += waitOutstockProductPojo.getProductNum();
                }

                ProductFieldPojo stockField = saasFormHelp.getProductFieldPojo(RedisPrefixConstant.PRODUCT_STOCK,ProductEnum.STOCK.getAttr(), corpid);
                Integer accuracy = stockField.getAccuracy();
                String numStr = attrDecimalPrecisionHelper.formatMoneyPrecision(num, accuracy);
                json.put("tableData", waitOutstockProductPojoList);
                json.put("previewText", String.format(I18nMessageUtil.getMessage(SaasConstant.WAIT_OUT_OF_STOCK_PRODUCTS), waitOutstockProductPojoList.size(), numStr));
                json.put("tableHead", getTableHead(businessType, subBusinessType));
                data.put(listOptionPackagePojo.getNeedOption8() ? ListOptionEnum.WAIT_INSTOCK_PRODUCT.getAttr() : ListOptionEnum.WAIT_OUTSTOCK_PRODUCT.getAttr(), json);
            }
        }
        if (listOptionPackagePojo.getNeedOption12()){
            String warehouse = listOptionPackagePojo.getProductSearchWarehouseMap().getOrDefault(dataId,new HashSet<>()).toString();
            warehouse = warehouse.substring(1,warehouse.length()-1);
            data.put(ListOptionEnum.STOCK_SEARCH.getAttr(),warehouse);
        }
        if (listOptionPackagePojo.getNeedOption13()){
            data.put(ListOptionEnum.WARNING_SEARCH.getAttr(),listOptionPackagePojo.getProductSearchMap().get(dataId));
        }
        if (listOptionPackagePojo.getNeedOption14()){
//            data.put(ListOptionEnum.GUARANTEE_SEARCH.getAttr(),listOptionPackagePojo.getProductSearchMap().get(dataId));
//            // 已过期数据前端标红
//            if (Objects.toString(listOptionPackagePojo.getProductSearchMap().get(dataId)).startsWith(GuaranteeStatusEnum.OUT_OF_DATE.getName())) {
//                data.put("redFlag", 1);
//            }
        }
        if (listOptionPackagePojo.getNeedOption15()){
            ProductWarehouseEntity productWarehouseEntity = entity.getProductWarehouseEntity();
            if (Objects.nonNull(productWarehouseEntity)) {
                data.put("currentStock", productWarehouseEntity.getNum());
                data.put("minimumStock", productWarehouseEntity.getStockLowerLimit());
                data.put("maximumStock", productWarehouseEntity.getStockUpperLimit());
                data.put(ProductEnum.WAREHOUSE.getAttr(), productWarehouseEntity.getWarehouseName());
                Double stockUpperLimt = Objects.isNull(productWarehouseEntity.getStockUpperLimit()) ? 0D : productWarehouseEntity.getStockUpperLimit();
                Double stockLowerLimt = Objects.isNull(productWarehouseEntity.getStockLowerLimit()) ? 0D : productWarehouseEntity.getStockLowerLimit();
                if (productWarehouseEntity.getNum() > stockUpperLimt) {
                    // 超上限
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("overLimitType", 1);
                    jsonObject.put("overNum", productWarehouseEntity.getNum() - stockUpperLimt);
                    data.put("option_15", jsonObject);
                } else {
                    // 超下限
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("overLimitType", 2);
                    jsonObject.put("overNum", stockLowerLimt - productWarehouseEntity.getNum());
                    data.put("option_15", jsonObject);
                }
            }
        }
        if (listOptionPackagePojo.getNeedOption16()){
            String enable = data.getString(DistributorAccountEnum.ACCOUNT_STATUS.getAttr());
            JSONObject optionObj = new JSONObject();
            List<ButtonPojo> buttonPojoList = new ArrayList<>();
            buttonPojoList.add(Objects.equals(enable, DistributorAccountStatusEnum.ENABLE.getName())  ? new ButtonPojo(ListOptionTabEnum.DISABLE) : new ButtonPojo(ListOptionTabEnum.ENABLE));
            optionObj.put("value", buttonPojoList);
            data.put(ListOptionEnum.ACCOUNT_ENABLE.getAttr(), optionObj);
        }
        String archivedTag = listOptionPackagePojo.getArchivedTag();
        if (!listOptionPackagePojo.getArchivedTag().isEmpty()) {
            // 客户归档标签
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && Objects.equals(data.getInteger(CustomerManagementEnum.IS_ARCHIVED.getAttr()), 1)) {
                JSONArray tagPojoList = tagData.getJSONArray(archivedTag);
                tagPojoList = tagPojoList == null ? new JSONArray() : tagPojoList;
                tagPojoList.add(new TagPojo(TagEnum.TAG_ARCHIVED));
                tagData.put(archivedTag, tagPojoList);
            }
            // 机会归档标签
            else if (Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode()) && Objects.equals(data.getInteger(SalesOpportunityEnum.IS_ARCHIVED.getAttr()), 1)) {
                JSONArray tagPojoList = tagData.getJSONArray(archivedTag);
                tagPojoList = tagPojoList == null ? new JSONArray() : tagPojoList;
                tagPojoList.add(new TagPojo(TagEnum.TAG_ARCHIVED_OPPORTUNITY));
                tagData.put(archivedTag, tagPojoList);
            }
            // 合同归档标签
            else if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode()) && Objects.equals(data.getInteger(ContractEnum.ARCHIVED.getAttr()), 1)) {
                JSONArray tagPojoList = tagData.getJSONArray(archivedTag);
                tagPojoList = tagPojoList == null ? new JSONArray() : tagPojoList;
                tagPojoList.add(new TagPojo(TagEnum.TAG_ARCHIVED_CONTRACT));
                tagData.put(archivedTag, tagPojoList);
            }
            // 订货单归档标签
            else if (Objects.equals(businessType, XbbRefTypeEnum.ORDER.getCode()) && Objects.equals(data.getInteger(OrderEnum.ARCHIVED.getAttr()), 1)) {
                JSONArray tagPojoList = tagData.getJSONArray(archivedTag);
                tagPojoList = tagPojoList == null ? new JSONArray() : tagPojoList;
                tagPojoList.add(new TagPojo(TagEnum.TAG_ARCHIVED_ORDER));
                tagData.put(archivedTag, tagPojoList);
            }
            //报价单归档标签
            else if (Objects.equals(businessType, XbbRefTypeEnum.QUOTATION.getCode()) && Objects.equals(data.getInteger(QuotationEnum.ARCHIVED.getAttr()), 1)) {
                JSONArray tagPojoList = tagData.getJSONArray(archivedTag);
                tagPojoList = tagPojoList == null ? new JSONArray() : tagPojoList;
                tagPojoList.add(new TagPojo(TagEnum.TAG_ARCHIVED_QUOTATION));
                tagData.put(archivedTag, tagPojoList);
            }
            // 线索归档标签
            if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode()) && Objects.equals(data.getInteger(ClueEnum.IS_ARCHIVED.getAttr()), 1)) {
                JSONArray tagPojoList = tagData.getJSONArray(archivedTag);
                tagPojoList = tagPojoList == null ? new JSONArray() : tagPojoList;
                tagPojoList.add(new TagPojo(TagEnum.TAG_ARCHIVED_CLUE));
                tagData.put(archivedTag, tagPojoList);
            }
            // 对账单归档标签
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_STATEMENT_STATISTIC.getCode()) && Objects.equals(data.getInteger(CustomerStatementStatisticEnum.IS_ARCHIVED.getAttr()), 1)) {
                JSONArray tagPojoList = tagData.getJSONArray(archivedTag);
                tagPojoList = tagPojoList == null ? new JSONArray() : tagPojoList;
                tagPojoList.add(new TagPojo(TagEnum.TAG_ARCHIVED_STATEMENT));
                tagData.put(archivedTag, tagPojoList);
            }
        }
        String publicTag = listOptionPackagePojo.getPublicTag();
        if (!publicTag.isEmpty()) {
            if (listOptionPackagePojo.getPublicTagMap().containsKey(dataId)) {
                JSONArray tagPojoList = tagData.getJSONArray(publicTag);
                tagPojoList = tagPojoList == null ? new JSONArray() : tagPojoList;
                TagPojo tagPojo = new TagPojo(TagEnum.TAG_RETURN_PUBLIC);
                tagPojo.setMemo(listOptionPackagePojo.getPublicTagMap().get(dataId));
                tagPojoList.add(tagPojo);
                tagData.put(publicTag, tagPojoList);
            }
        }
        String transferTag = listOptionPackagePojo.getTransferTag();
        if (StringUtil.isNotEmpty(transferTag)) {
            if (listOptionPackagePojo.getTransferTagMap().containsKey(dataId)) {
                JSONArray tagPojoList = tagData.getJSONArray(transferTag);
                tagPojoList = tagPojoList == null ? new JSONArray() : tagPojoList;
                TagPojo tagPojo = new TagPojo(TagEnum.TAG_TRANSFER_PUBLIC_CUSTOMER);
                tagPojo.setMemo(listOptionPackagePojo.getTransferTagMap().get(dataId));
                tagPojoList.add(tagPojo);
                tagData.put(transferTag, tagPojoList);
            }
        }
        String emergencyTag = listOptionPackagePojo.getEmergencyTag();
        if (!emergencyTag.isEmpty()) {
            String emergencyStr = data.getString(WorkOrderEnum.EMERGENCY_LEVEL.getAttr());
            if (!(Objects.isNull(emergencyStr) || emergencyStr.isEmpty() || Objects.equals(emergencyStr, "0"))) {
                JSONArray tagPojoList = tagData.getJSONArray(archivedTag);
                tagPojoList = tagPojoList == null ? new JSONArray() : tagPojoList;
                tagPojoList.add(Objects.equals(emergencyStr, "1") ? new TagPojo(TagEnum.TAG_EMERGENCY) : new TagPojo(TagEnum.TAG_VERT_EMERGENCY));
                tagData.put(emergencyTag, tagPojoList);
            }
        }
        //应收款逾期标签
        String overdueTag = listOptionPackagePojo.getOverdueTag();
        String status = FastJsonHelper.getStringOrDefaultFromFormData(data,PaymentEnum.STATUS.getAttr(),PaymentStatusEnum.UN_RECEIVABLES.getCode());
        if (Objects.equals(status, PaymentStatusEnum.UN_RECEIVABLES.getCode()) || Objects.equals(status, PaymentStatusEnum.PARTIAL_RECEIPTS.getCode()) ) {
            if (Objects.nonNull(overdueTag) && !Objects.equals(overdueTag, "")) {
                Long estimateTime = FastJsonHelper.getLongOrDefaultFromFormData(data, PaymentEnum.ESTIMATE_TIME.getAttr(), 0L);
                Double unAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(data, PaymentEnum.UN_AMOUNT.getAttr(), 0D);
                if (Objects.nonNull(estimateTime) && estimateTime < DateUtil.getTodayInt() && unAmount > 0) {
                    JSONArray tagPojoList = tagData.getJSONArray(overdueTag);
                    tagPojoList = tagPojoList == null ? new JSONArray() : tagPojoList;
                    tagPojoList.add(new TagPojo(TagEnum.TAG_OVERDUE));
                    tagData.put(overdueTag, tagPojoList);
                }
            }
        }
    }

    public void setHeadList(List<FieldAttrEntity> headList, ListOptionPackagePojo listOptionPackagePojo, Integer subBusinessType , Integer businessType) {
        if (listOptionPackagePojo.getNeedOption12()){
            FieldAttrEntity fieldStockSearch = new FieldAttrEntity();
            fieldStockSearch.setAttr(ListOptionEnum.STOCK_SEARCH.getAttr());
            fieldStockSearch.setAttrName(ListOptionEnum.STOCK_SEARCH.getAttrName());
            fieldStockSearch.setFieldType(FieldTypeEnum.TEXT.getType());
            fieldStockSearch.setDisableListSort(1);
            headList.add(0,fieldStockSearch);
        }
        if (listOptionPackagePojo.getNeedOption13()){
            FieldAttrEntity fieldStockSearch = new FieldAttrEntity();
            fieldStockSearch.setAttr(ListOptionEnum.WARNING_SEARCH.getAttr());
            fieldStockSearch.setAttrName(ListOptionEnum.WARNING_SEARCH.getAttrName());
            fieldStockSearch.setFieldType(FieldTypeEnum.TEXT.getType());
            fieldStockSearch.setDisableListSort(1);
            headList.add(0,fieldStockSearch);
        }
        if (listOptionPackagePojo.getNeedOption14()){

        }
        if (listOptionPackagePojo.getNeedOption7()) {
            FieldAttrEntity fieldStockSearch = new FieldAttrEntity();
            fieldStockSearch.setAttr(ListOptionEnum.MULTI_SPEC.getAttr());
            fieldStockSearch.setAttrName(ListOptionEnum.MULTI_SPEC.getAttrName());
            fieldStockSearch.setFieldType(FieldTypeEnum.STOCK_SEARCH.getType());
            fieldStockSearch.setDisableListSort(1);
            if (Objects.equals(subBusinessType, XbbRefTypeEnum.STOCK_SEARCH.getCode())) {
                fieldStockSearch.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.STOCK_DISTRIBUTED));
                fieldStockSearch.setDefaultName(I18nMessageUtil.getMessage(I18nStringConstant.STOCK_DISTRIBUTED));
            }
            headList.add(0, fieldStockSearch);
        }
        if (listOptionPackagePojo.getNeedOption15()) {
            FieldAttrEntity fieldWarningSearch = new FieldAttrEntity();
            fieldWarningSearch.setAttr(ListOptionEnum.OVER_LIMIT_NUM.getAttr());
            fieldWarningSearch.setAttrName(ListOptionEnum.OVER_LIMIT_NUM.getAttrName());
            fieldWarningSearch.setFieldType(FieldTypeEnum.WARNING_SEARCH.getType());
            fieldWarningSearch.setDisableListSort(1);
            headList.add(fieldWarningSearch);
        }
        if (listOptionPackagePojo.getNeedOption5()) {
            FieldAttrEntity fieldContract = new FieldAttrEntity();
            fieldContract.setAttr(ListOptionEnum.WAIT_PURCHASE_CONTRACT.getAttr());
            fieldContract.setAttrName(ListOptionEnum.WAIT_PURCHASE_CONTRACT.getAttrName());
            fieldContract.setFieldType(FieldTypeEnum.CONTRACT.getType());
            fieldContract.setSaasAttr(XbbRefTypeEnum.WAIT_PURCHASE.getAlias());
            fieldContract.setLinkedType(XbbRefTypeEnum.PURCHASE.getCode());
            fieldContract.setDisableListSort(1);
            headList.add(fieldContract);
        }
        if (listOptionPackagePojo.getNeedOption6()) {
            FieldAttrEntity fieldContract = new FieldAttrEntity();
            fieldContract.setAttr(ListOptionEnum.WAIT_PURCHASE_PRODUCT.getAttr());
            fieldContract.setAttrName(ListOptionEnum.WAIT_PURCHASE_PRODUCT.getAttrName());
            fieldContract.setFieldType(FieldTypeEnum.PRODUCT.getType());
            fieldContract.setSaasAttr(XbbRefTypeEnum.WAIT_PURCHASE.getAlias());
            fieldContract.setLinkedType(XbbRefTypeEnum.PURCHASE.getCode());
            fieldContract.setDisableListSort(1);
            headList.add(fieldContract);
        }
        if (listOptionPackagePojo.getNeedOption8()) {
            if (Objects.equals(businessType , XbbRefTypeEnum.PURCHASE.getCode())){
                FieldAttrEntity fieldContract = new FieldAttrEntity();
                fieldContract.setAttr(ListOptionEnum.WAIT_INSTOCK_PRODUCT.getAttr());
                fieldContract.setAttrName(ListOptionEnum.WAIT_INSTOCK_PRODUCT.getAttrName());
                fieldContract.setFieldType(FieldTypeEnum.WAIT_INSTOCK_CONTRACT.getType());
                fieldContract.setSaasAttr(XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getAlias());
                fieldContract.setLinkedType(XbbRefTypeEnum.PURCHASE_INSTOCK.getCode());
                fieldContract.setDisableListSort(1);
                headList.add(fieldContract);
            }
        }
        if (listOptionPackagePojo.getNeedOption9()) {
            if (Objects.equals(businessType , XbbRefTypeEnum.CONTRACT.getCode())) {
                FieldAttrEntity fieldContract = new FieldAttrEntity();
                fieldContract.setAttr(ListOptionEnum.WAIT_OUTSTOCK_PRODUCT.getAttr());
                fieldContract.setAttrName(ListOptionEnum.WAIT_OUTSTOCK_PRODUCT.getAttrName());
                fieldContract.setFieldType(FieldTypeEnum.WAIT_OUTSTOCK_PRODUCT.getType());
                fieldContract.setSaasAttr(XbbRefTypeEnum.WAIT_OUTSTOCK.getAlias());
                fieldContract.setLinkedType(XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode());
                fieldContract.setDisableListSort(1);
                headList.add(fieldContract);
            }
        }
        if (listOptionPackagePojo.getNeedOption10()) {
            FieldAttrEntity fieldContract = new FieldAttrEntity();
            fieldContract.setAttr(ListOptionEnum.WAIT_PRODUCE_CONTRACT.getAttr());
            fieldContract.setAttrName(ListOptionEnum.WAIT_PRODUCE_CONTRACT.getAttrName());
            fieldContract.setFieldType(FieldTypeEnum.CONTRACT.getType());
            fieldContract.setLinkedType(XbbRefTypeEnum.PRODUCTION_ORDER.getCode());
            fieldContract.setSaasAttr(XbbRefTypeEnum.WAIT_PRODUCE.getAlias());
            fieldContract.setDisableListSort(1);
            headList.add(fieldContract);
        }
        if (listOptionPackagePojo.getNeedOption11()) {
            FieldAttrEntity fieldContract = new FieldAttrEntity();
            fieldContract.setAttr(ListOptionEnum.WAIT_PRODUCE_PRODUCT.getAttr());
            fieldContract.setAttrName(ListOptionEnum.WAIT_PRODUCE_PRODUCT.getAttrName());
            fieldContract.setFieldType(FieldTypeEnum.PRODUCT.getType());
            fieldContract.setLinkedType(XbbRefTypeEnum.PRODUCTION_ORDER.getCode());
            fieldContract.setSaasAttr(XbbRefTypeEnum.WAIT_PRODUCE.getAlias());
            fieldContract.setDisableListSort(1);
            headList.add(fieldContract);
        }
        if (listOptionPackagePojo.getNeedOption4()) {
            FieldAttrEntity fieldFlow = new FieldAttrEntity();
            fieldFlow.setAttr(ListOptionEnum.FLOW.getAttr());
            fieldFlow.setAttrName(ListOptionEnum.FLOW.getAttrName());
            fieldFlow.setFieldType(FieldTypeEnum.FLOW.getType());
            fieldFlow.setDisableListSort(1);
            headList.add(0, fieldFlow);
        }
        if (listOptionPackagePojo.getNeedOption3()) {
            FieldAttrEntity fieldCall = new FieldAttrEntity();
            fieldCall.setAttr(ListOptionEnum.CALL.getAttr());
            fieldCall.setAttrName(ListOptionEnum.CALL.getAttrName());
            fieldCall.setFieldType(FieldTypeEnum.CALL.getType());
            fieldCall.setDisableListSort(1);
            headList.add(0, fieldCall);
        }
        if (listOptionPackagePojo.getNeedOption2()) {
            FieldAttrEntity fieldRemind = new FieldAttrEntity();
            fieldRemind.setAttr(ListOptionEnum.REMIND.getAttr());
            fieldRemind.setAttrName(ListOptionEnum.REMIND.getAttrName());
            fieldRemind.setFieldType(FieldTypeEnum.REMIND.getType());
            fieldRemind.setDisableListSort(1);
            headList.add(0, fieldRemind);
        }
        if (listOptionPackagePojo.getNeedOption1()) {
            FieldAttrEntity fieldFocus = new FieldAttrEntity();
            fieldFocus.setAttr(ListOptionEnum.FOCUS.getAttr());
            fieldFocus.setAttrName(ListOptionEnum.FOCUS.getAttrName());
            fieldFocus.setFieldType(FieldTypeEnum.FOCUS.getType());
            fieldFocus.setDisableListSort(1);
            headList.add(0, fieldFocus);
        }
        if (listOptionPackagePojo.getNeedOption0() && (!listOptionPackagePojo.getOptionList().isEmpty()) || listOptionPackagePojo.getProductionOrderFinish() || listOptionPackagePojo.getOnline() || Objects.equals(subBusinessType, XbbRefTypeEnum.SEQ_SEARCH.getCode())
                || listOptionPackagePojo.getFreeze() || listOptionPackagePojo.getRevoke() || listOptionPackagePojo.getStatement()) {
            // 库存查询列表页没有操作按钮
            FieldAttrEntity fiedlOption = new FieldAttrEntity();
            fiedlOption.setAttr(ListOptionEnum.OPTION.getAttr());
            fiedlOption.setAttrName(ListOptionEnum.OPTION.getAttrName());
            fiedlOption.setFieldType(FieldTypeEnum.OPTION.getType());
            fiedlOption.setDisableListSort(1);
            if (Objects.equals(subBusinessType, XbbRefTypeEnum.SEQ_SEARCH.getCode())) {
                fiedlOption.setFieldType(FieldTypeEnum.SEQ_TRACK.getType());
                headList.add(headList.size(), fiedlOption);
            } else {
                headList.add(0, fiedlOption);
            }
        }
        if (listOptionPackagePojo.getNeedOption16()) {
            FieldAttrEntity attrEntity = new FieldAttrEntity();
            attrEntity.setAttr(ListOptionEnum.ACCOUNT_ENABLE.getAttr());
            attrEntity.setAttrName(ListOptionEnum.ACCOUNT_ENABLE.getAttrName());
            attrEntity.setFieldType(FieldTypeEnum.OPTION.getType());
            attrEntity.setDisableListSort(1);
            headList.add(0, attrEntity);
        }
    }

    private ListOptionPackagePojo setOptionBase(List<Long> dataIdList, FormDataListDTO formDataListDTO, PaasFormDataEsListVO formDataEsListVO, Long currentModelType) throws XbbException {
        if (Objects.equals(1, formDataListDTO.getDefaultGroup()) && Objects.equals(formDataListDTO.getListGroupId(), Long.valueOf(ListGroupEnum.APPROVAL.getCode()))) {
            return new ListOptionPackagePojo();
        }
        String corpid = formDataListDTO.getCorpid();
        String userId = formDataListDTO.getUserId();
        Integer businessType = formDataListDTO.getBusinessType();
        Integer subBusinessType = formDataListDTO.getSubBusinessType();
        Integer distributorMark = formDataListDTO.getDistributorMark();
        ListOptionPackagePojo listOptionPackagePojo = new ListOptionPackagePojo();
        List<ButtonPojo> optionList = listOptionPackagePojo.getOptionList();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(subBusinessType);
        List<PaasFormDataEntityExt> list = formDataEsListVO.getPaasFormDataESList();
        Set<String> permSet = formDataListDTO.getLoginUser().getPermSet();
        Map<String, String> unitItemMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        switch (xbbRefTypeEnum) {
            case CUSTOMER_MANAGEMENT:
            case CUSTOMER:
            case CUSTOMER_FOCUS:
            case CUSTOMER_DEAL:
            case CUSTOMER_FOLLOW:
                //关注
                boolean isCusShare;
                try {
                    isCusShare = companyConfigModel.hasBeenEnable(corpid, CompanyConfigEnum.SHARE_FOCUS_CUSTOEMR.getAlias(), BasicConstant.IS_USE.toString());
                } catch (XbbException e) {
                    isCusShare = Objects.equals(CompanyConfigEnum.SHARE_FOCUS_CUSTOEMR.getValue(), BasicConstant.IS_USE.toString());
                }
                listOptionPackagePojo.setNeedOption1(true);
                Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                map.put("corpid", corpid);
                if(!isCusShare) {
                    map.put("userId", userId);
                }
                map.put("customerIdIn", dataIdList);
                map.put("del", 0);
                map.put("focus", 1);
                List<CustomerFocusEntity> customerFocusEntityList = customerFocusModel.findEntitys(map);
                for (CustomerFocusEntity entity : customerFocusEntityList) {
                    listOptionPackagePojo.getFocusList().add(entity.getCustomerId());
                }
                //跟进
                listOptionPackagePojo.setNeedOption4(formDataListDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.CUSTOMER_COMMUNICATE_VIEW.getAlias()));
                getCommunicate(formDataListDTO, corpid, listOptionPackagePojo, dataIdList);
                //提醒
                listOptionPackagePojo.setNeedOption2(true);
                getPushNotify(dataIdList, corpid, businessType, listOptionPackagePojo.getPushNotifyList());
                // 判断是否有呼叫权限
                boolean isActiveCall = callCenterCommonService.isOpenCallAndAgent(corpid, userId);
                // 判断是否有阿里云呼叫中心权限
                boolean isActiveAliyunCall = callCenterCommonService.isActiveAliyunCall(corpid,userId).IsActiveAliyunAndHasRole();
                if (isActiveCall||isActiveAliyunCall) {
                    listOptionPackagePojo.setNeedOption3(true);
                }
                //标签
                listOptionPackagePojo.setArchivedTag(CustomerManagementEnum.NAME.getAttr() + "Tag");
                listOptionPackagePojo.setPublicTag(CustomerManagementEnum.NAME.getAttr() + "Tag");
                listOptionPackagePojo.setPublicTagMap(tagLinkModel.getPublicTag(corpid, dataIdList));
                for (FieldAttrEntity fieldAttrEntity : formDataEsListVO.getHeadList()) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.NAME.getAttr())) {
                        fieldAttrEntity.setTagAttr(CustomerManagementEnum.NAME.getAttr() + "Tag");
                        break;
                    }
                }
                break;
            case CUSTOMER_PUBLIC:
                // 判断是否有阿里云呼叫中心权限
                isActiveAliyunCall = callCenterCommonService.isActiveAliyunCall(corpid,userId).IsActiveAliyunAndHasRole();
                if (isActiveAliyunCall) {
                    listOptionPackagePojo.setNeedOption3(true);
                }
                //跟进
                listOptionPackagePojo.setNeedOption4(true);
                getCommunicate(formDataListDTO, corpid, listOptionPackagePojo, dataIdList);
                if (permSet.contains(ProPermissionAliasEnum.CUSTOMER_GAIN.getAlias())) {
                    optionList.add(new ButtonPojo(ListOptionTabEnum.GRAB));
                }
                // ‘归’标签
                listOptionPackagePojo.setArchivedTag(CustomerManagementEnum.NAME.getAttr() + "Tag");
                for (FieldAttrEntity fieldAttrEntity : formDataEsListVO.getHeadList()) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.NAME.getAttr())) {
                        fieldAttrEntity.setTagAttr(CustomerManagementEnum.NAME.getAttr() + "Tag");
                        break;
                    }
                }
                // ‘转移’标签
                listOptionPackagePojo.setTransferTag(CustomerManagementEnum.NAME.getAttr() + "Tag");
                for (FieldAttrEntity fieldAttrEntity : formDataEsListVO.getHeadList()) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.NAME.getAttr())) {
                        fieldAttrEntity.setTagAttr(CustomerManagementEnum.NAME.getAttr() + "Tag");
                        break;
                    }
                }
                listOptionPackagePojo.setTransferTagMap(tagLinkModel.getTransferTag(corpid, dataIdList,XbbRefTypeEnum.CUSTOMER_TRANSFER.getCode()));
                break;
            case CUSTOMER_RECYCLE:
                optionList.clear();
                // 判断是否有阿里云呼叫中心权限
                isActiveAliyunCall = callCenterCommonService.isActiveAliyunCall(corpid,userId).IsActiveAliyunAndHasRole();
                if (isActiveAliyunCall) {
                    listOptionPackagePojo.setNeedOption3(true);
                }
                break;
            case CONTRACT:
                //提醒
                listOptionPackagePojo.setNeedOption2(true);
                getPushNotify(dataIdList, corpid, businessType, listOptionPackagePojo.getPushNotifyList());
                // ‘归’标签
                listOptionPackagePojo.setArchivedTag(ContractEnum.CONTRACT_NO.getAttr() + "Tag");
                for (FieldAttrEntity fieldAttrEntity : formDataEsListVO.getHeadList()) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.CONTRACT_NO.getAttr())) {
                        fieldAttrEntity.setTagAttr(ContractEnum.CONTRACT_NO.getAttr() + "Tag");
                        break;
                    }
                }
                break;
            case QUOTATION:
                //提醒
                listOptionPackagePojo.setNeedOption2(true);
                getPushNotify(dataIdList, corpid, businessType, listOptionPackagePojo.getPushNotifyList());
                // ‘归’标签
                listOptionPackagePojo.setArchivedTag(QuotationEnum.QUOTATION_NO.getAttr() + "Tag");
                for (FieldAttrEntity fieldAttrEntity : formDataEsListVO.getHeadList()) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), QuotationEnum.QUOTATION_NO.getAttr())) {
                        fieldAttrEntity.setTagAttr(QuotationEnum.QUOTATION_NO.getAttr() + "Tag");
                        break;
                    }
                }
                break;
            case CONTACT:
                // 判断是否有呼叫权限
                boolean activeCall = callCenterCommonService.isOpenCallAndAgent(corpid, userId);
                // 判断是否有阿里云呼叫中心权限
                isActiveAliyunCall = callCenterCommonService.isActiveAliyunCall(corpid,userId).IsActiveAliyunAndHasRole();
                if (activeCall||isActiveAliyunCall) {
                    listOptionPackagePojo.setNeedOption3(true);
                }
                break;
            case SALES_OPPORTUNITY:
            case ALL_OPPORTUNITY:
            case KEY_OPPORTUNITY:
                //关注
                boolean isOppShare;
                try {
                    isOppShare = companyConfigModel.hasBeenEnable(corpid, CompanyConfigEnum.SHARE_FOCUS_OPPORTUNITY.getAlias(), BasicConstant.IS_USE.toString());
                } catch (XbbException e) {
                    isOppShare = Objects.equals(CompanyConfigEnum.SHARE_FOCUS_OPPORTUNITY.getValue(), BasicConstant.IS_USE.toString());
                }
                listOptionPackagePojo.setNeedOption1(true);
                map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                map.put("corpid", corpid);
                if(!isOppShare) {
                    map.put("userId", userId);
                }
                map.put("opportunityIdIn", dataIdList);
                map.put("del", 0);
                map.put("focus", 1);
                List<OpportunityFocusEntity> opportunityFocusEntityList = opportunityFocusModel.findEntitys(map);
                for (OpportunityFocusEntity entity : opportunityFocusEntityList) {
                    listOptionPackagePojo.getFocusList().add(entity.getOpportunityId());
                }
                //提醒
                listOptionPackagePojo.setNeedOption2(true);
                getPushNotify(dataIdList, corpid, businessType, listOptionPackagePojo.getPushNotifyList());
                // ‘归’标签
                listOptionPackagePojo.setArchivedTag(SalesOpportunityEnum.SERIAL_NO.getAttr() + "Tag");
                for (FieldAttrEntity fieldAttrEntity : formDataEsListVO.getHeadList()) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), SalesOpportunityEnum.SERIAL_NO.getAttr())) {
                        fieldAttrEntity.setTagAttr(SalesOpportunityEnum.SERIAL_NO.getAttr() + "Tag");
                        break;
                    }
                }
                break;
            case SUPPLIER:
                //提醒
                listOptionPackagePojo.setNeedOption2(true);
                getPushNotify(dataIdList, corpid, businessType, listOptionPackagePojo.getPushNotifyList());
                break;
            case SUPPLIER_CONTACT:
                break;
            case PURCHASE:
                //提醒
                listOptionPackagePojo.setNeedOption2(true);
                getPushNotify(dataIdList, corpid, businessType, listOptionPackagePojo.getPushNotifyList());
                break;
            case PAYMENT:
                ButtonPojo paymentWriteOff = new ButtonPojo(ListOptionTabEnum.PAYMENT_WRITE_OFF, XbbRefTypeEnum.PAYMENT.getCode(), distributorMark);
                paymentWriteOff.setLinkBusinessType(XbbRefTypeEnum.PAYMENT_SHEET.getCode());
                optionList.add(paymentWriteOff);
                optionList.add(new ButtonPojo(ListOptionTabEnum.ADDPAYMENT, XbbRefTypeEnum.PAYMENT_SHEET.getCode(), distributorMark));
                if (!Objects.equals(ModelTypeEnum.INVOICE.getCode(), currentModelType)) {
                    //非开票模式才可能有新建发票按钮
                    optionList.add(new ButtonPojo(ListOptionTabEnum.ADDINVOICE, XbbRefTypeEnum.INVOICE.getCode(), distributorMark));
                }
                //paymentCheckInvoiceOption(formDataListDTO,list,listOptionPackagePojo,XbbRefTypeEnum.PAYMENT);
                checkInvoiceOption(formDataListDTO,list,listOptionPackagePojo,XbbRefTypeEnum.PAYMENT);

                listOptionPackagePojo.setOverdueTag(PaymentEnum.PAYMENT_NO.getAttr() + "Tag");
                for (FieldAttrEntity fieldAttrEntity : formDataEsListVO.getHeadList()) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.PAYMENT_NO.getAttr())) {
                        fieldAttrEntity.setTagAttr(PaymentEnum.PAYMENT_NO.getAttr() + "Tag");
                        break;
                    }
                }
                break;
            case PAY_PLAN:
                optionList.add(new ButtonPojo(ListOptionTabEnum.ADDPAYPLAN, XbbRefTypeEnum.PAY_SHEET.getCode()));
                optionList.add(new ButtonPojo(ListOptionTabEnum.ADDPURCHASEINVOICE, XbbRefTypeEnum.PURCHASE_INVOICE.getCode()));
                checkInvoiceOption(formDataListDTO,list,listOptionPackagePojo,XbbRefTypeEnum.PAY_PLAN);
                break;
            case INVOICE:
                if (Objects.isNull(formDataListDTO.getListGroupId())) {
                    // fix: 26079 【紧急】销售出库单详情页关联列表报服务器开小差
                    break;
                }
                if (Objects.equals(formDataListDTO.getListGroupId().intValue(),BasicConstant.ZERO) || Objects.equals(formDataListDTO.getListGroupId().intValue(),ListGroupEnum.INVOICE_NORMAL.getCode())){
                    if (permSet.contains(ProPermissionAliasEnum.INVOICE_CANCEL.getAlias())) {
                        ButtonPojo buttonPojo = new ButtonPojo(ListOptionTabEnum.CANCEL);
                        buttonPojo.setDistributorMark(distributorMark);
                        optionList.add(buttonPojo);
                    }
                    if (permSet.contains(ProPermissionAliasEnum.INVOICE_RED.getAlias())) {
                        ButtonPojo buttonPojo = new ButtonPojo(ListOptionTabEnum.RED);
                        buttonPojo.setDistributorMark(distributorMark);
                        optionList.add(buttonPojo);
                    }
                    Map<Long, Double> redTotalMoneyByIdMap = invoiceService.getRedTotalMoneyByIdIn(dataIdList,new ArrayList<>(), corpid);
                    listOptionPackagePojo.setRedTotalMoneyByIdMap(redTotalMoneyByIdMap);
                }else if (Objects.equals(formDataListDTO.getListGroupId().intValue(),ListGroupEnum.INVOICE_CANCEL.getCode())){
                    ButtonPojo buttonPojo = new ButtonPojo(ListOptionTabEnum.INVOICE_REVERT);
                    buttonPojo.setDistributorMark(distributorMark);
                    optionList.add(buttonPojo);
                }
                listOptionPackagePojo.setCrossMonth(true);
                break;
            case PURCHASE_INVOICE:
                if(Objects.equals(formDataListDTO.getListGroupId(),BasicConstant.ZERO_LONG)
                        || Objects.equals(formDataListDTO.getListGroupId(), Long.valueOf(ListGroupEnum.PURCHASE_INVOICE_NORMAL.getCode()))){
                    if(permSet.contains(ProPermissionAliasEnum.PURCHASE_INVOICE_CANCEL.getAlias())){
                        optionList.add(new ButtonPojo(ListOptionTabEnum.PURCHASE_INVOICE_CANCEL));
                    }
                    if(permSet.contains(ProPermissionAliasEnum.PURCHASE_INVOICE_RED.getAlias())){
                        optionList.add(new ButtonPojo(ListOptionTabEnum.PURCHASE_INVOICE_RED));
                    }
                    Map<Long,Double> redTotalMoneyByIdMap = purchaseInvoiceService.getRedTotalMoneyByIdIn(dataIdList,new ArrayList<>(),corpid);
                    listOptionPackagePojo.setRedTotalMoneyByIdMap(redTotalMoneyByIdMap);
                }else if(Objects.equals(formDataListDTO.getListGroupId(), Long.valueOf(ListGroupEnum.PURCHASE_INVOICE_CANCEL.getCode()))){
                    optionList.add(new ButtonPojo(ListOptionTabEnum.PURCHASE_INVOICE_REVERT));
                }
                listOptionPackagePojo.setCrossMonth(true);
                break;
            case PRODUCT:
                // 获取产品表单解释
                PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
                listOptionPackagePojo.setProductExplainMap(ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null));
                listOptionPackagePojo.setOnline(true);
                // 判断规格是否启用或不可见
                List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
                for (int i = 0; i < explainList.size(); i++) {
                    FieldAttrEntity fieldAttrEntity = explainList.get(i);
                    if (Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.SPECIFICATION.getAttr())){
                        if (Objects.equals(fieldAttrEntity.getVisible(),1) && Objects.equals(fieldAttrEntity.getIsOpen(),1)){
                            listOptionPackagePojo.setNeedOption7(true);
                        }
                    }
                }
                listOptionPackagePojo.setProductMap(productListHelp.childProductList(formDataListDTO, dataIdList,corpid, listOptionPackagePojo.getProductExplainMap()));
                listOptionPackagePojo.setCategoryMap(productListHelp.categoryList(corpid));
                // productService.productStockList(formDataListDTO, formDataEsListVO);
                break;
            case WAIT_PURCHASE:
            case WAIT_PRODUCE:
                optionList.clear();
                Integer isProduce;
                if (Objects.equals(XbbRefTypeEnum.WAIT_PURCHASE.getCode(), subBusinessType)) {
                    optionList.add(new ButtonPojo(ListOptionTabEnum.PURCHASE, XbbRefTypeEnum.PURCHASE.getCode()));
                    isProduce = ContractProduceEnum.WAIT_PURCHASE.getCode();
                } else {
                    if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                        optionList.add(new ButtonPojo(ListOptionTabEnum.PRODUCE, XbbRefTypeEnum.PRODUCTION_ORDER.getCode(), ListOptionEnum.WAIT_PRODUCE_CONTRACT.getAttr()));
                    } else {
                        optionList.add(new ButtonPojo(ListOptionTabEnum.PRODUCE, XbbRefTypeEnum.PRODUCTION_ORDER.getCode()));
                    }
                    isProduce = ContractProduceEnum.WAIT_PRODUCE.getCode();
                }
                if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                    if (Objects.equals(subBusinessType, XbbRefTypeEnum.WAIT_PURCHASE.getCode())) {
                        listOptionPackagePojo.setNeedOption5(true);
                    } else {
                        listOptionPackagePojo.setNeedOption10(true);
                    }
                    listOptionPackagePojo.setWaitProductPojoMap(getWaitContractProductPojoMap(corpid,dataIdList,subBusinessType,isProduce));
                } else if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
                    if (Objects.equals(subBusinessType, XbbRefTypeEnum.WAIT_PURCHASE.getCode())) {
                        listOptionPackagePojo.setNeedOption6(true);
                    } else {
                        listOptionPackagePojo.setNeedOption11(true);
                    }
                    Map<Long,Double> stockMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    for (PaasFormDataEntityExt entityExt : formDataEsListVO.getPaasFormDataESList()){
                        stockMap.put(entityExt.getDataId(),entityExt.getData().getDouble(ProductEnum.STOCK.getAttr()));
                    }
                    Map<Long,Double> lackStockMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    Map<Long,List<Long>> productAndContractIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    listOptionPackagePojo.setWaitContractPojoMap(getWaitContractPojoMap(corpid,dataIdList,lackStockMap,isProduce,productAndContractIdMap,stockMap));
                    listOptionPackagePojo.setLackStockMap(lackStockMap);
                    listOptionPackagePojo.setProductAndContractIdMap(productAndContractIdMap);
                }
                break;
            case STOCK_SEARCH:
                List<Long> warehouseIdList = formDataListDTO.getSelectWarehouseIdList();
                Map<String, FieldAttrEntity> explainMap;
                if (Objects.nonNull(formDataEsListVO.getExplainMap())) {
                    explainMap = formDataEsListVO.getExplainMap();
                } else {
                    PaasFormExplainEntity paasFormExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
                    explainMap = ExplainUtil.getExplainMap(paasFormExplain.getExplains(), null);
                }
                listOptionPackagePojo.setProductExplainMap(explainMap);
                listOptionPackagePojo.setProductMap(productListHelp.productWarehouseList(formDataListDTO, list, dataIdList, corpid, warehouseIdList, explainMap));
                listOptionPackagePojo.setCategoryMap(productListHelp.categoryList(corpid));
                listOptionPackagePojo.setNeedOption0(false);
                listOptionPackagePojo.setNeedOption7(true);
                listOptionPackagePojo.setNeedOption12(false);
                break;
            case WARNING_SEARCH:
                listOptionPackagePojo.setNeedOption0(false);
                listOptionPackagePojo.setNeedOption15(true);
                break;
            case GUARANTEE_SEARCH:
                Map<Long,String> productSearchMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                listOptionPackagePojo.setProductMap(productListHelp.batchInfo(dataIdList,corpid,formDataListDTO,formDataEsListVO,productSearchMap));
                listOptionPackagePojo.setCategoryMap(productListHelp.categoryList(corpid));
                listOptionPackagePojo.setProductSearchMap(productSearchMap);
                listOptionPackagePojo.setNeedOption0(false);
                listOptionPackagePojo.setNeedOption7(false);
                listOptionPackagePojo.setNeedOption14(true);
                break;
            case WAIT_INSTOCK_PURCHASE:
                optionList.clear();
                optionList.add(new ButtonPojo(ListOptionTabEnum.INSTOCK, XbbRefTypeEnum.PURCHASE_INSTOCK.getCode()));
                listOptionPackagePojo.setNeedOption8(true);
                List<PurchaseProductEntity> purchaseProductEntityList = new ArrayList<>();
                List<FieldAttrEntity> headListExplain = new ArrayList<>();
                Map<Long,ProductEntityExt> productMap = new HashMap<>();
                ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
                if (Objects.equals(businessType,XbbRefTypeEnum.PRODUCT.getCode())){
                    purchaseProductEntityList = saasHelp.getWaitInStockProduct(corpid, formDataListDTO.getPurchaseProductEntityList());
                }else if (Objects.equals(businessType , XbbRefTypeEnum.PURCHASE.getCode())){
                    List<Long> purchaseIdList = new ArrayList<>();
                    for (PaasFormDataEntityExt entity : list) {
                        purchaseIdList.add(entity.getDataId());
                    }
                    purchaseProductEntityList = saasHelp.getPurchasetProductWaitInStock(formDataListDTO.getCorpid(), purchaseIdList);
                    //获取产品的解释
                    PaasFormDataEsListVO paasFormDataList = new PaasFormDataEsListVO();
                    paasFormDataList.setExplainMap(formDataEsListVO.getExplainMap());
                    FormDataListDTO formDataList = new FormDataListDTO();
                    formDataList.setCorpid(formDataListDTO.getCorpid());
                    formDataList.setExplainMap(formDataListDTO.getExplainMap());
                    headListExplain = setProductFormExplain(formDataList , paasFormDataList);
                    //获取关联的产品信息
                    List<Long> productIdList = new ArrayList<>();
                    purchaseProductEntityList.forEach(purchaseProductEntity -> productIdList.add(purchaseProductEntity.getProductId()));
                    productMap = productModel.getProductMapByIdIn(corpid,productIdList,0);
                    //处理用户与团队信息
                    Map<String, FieldAttrEntity> expalinMap = ExplainUtil.getExplainMapByList(headListExplain);
                    UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
                    userAndDepartmentGetDTO.setLoginUser(formDataListDTO.getLoginUser());
                    userAndDepartmentGetDTO.setUserId(formDataListDTO.getUserId());
                    userAndDepartmentGetDTO.setCorpid(corpid);
                    UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
                    Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
                    Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
                    parseSingleRowDataDTO.setExplainMap(expalinMap);
                    parseSingleRowDataDTO.setUserMap(userMap);
                    parseSingleRowDataDTO.setDepartmentMap(departmentMap);
                    parseSingleRowDataDTO.setLoginUser(formDataListDTO.getLoginUser());
                    parseSingleRowDataDTO.setUserId(formDataListDTO.getUserId());
                    parseSingleRowDataDTO.setCorpid(corpid);
                }
                Set<Long> productIdSet = new HashSet<>();
                for (PurchaseProductEntity entity : purchaseProductEntityList) {
                    productIdSet.add(entity.getProductId());
                }
                Map<Long, ProductEntityExt> productMap1 = getProductMap(productIdSet, corpid);
                Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
                Map<Long, List<UnitItemPoJo>> groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
                List<ItemPoJo> productItems = relativeProductHelp.getBusinessUnitItems(corpid);
                productItems.forEach(item -> unitItemMap.put(item.getValue().toString(), item.getText()));
                Integer accuracy = 6;
                for (PurchaseProductEntity entity : purchaseProductEntityList) {
                    if (Objects.equals(businessType , XbbRefTypeEnum.PRODUCT.getCode())){
                        entity.setWaitInstockNum(entity.getProductNum());
                    }
                    if (Objects.nonNull(entity.getBusinessUnit())) {
                        List<UnitItemPoJo> unitItemPoJos = groupItemsMap.get(entity.getGroupId());
                        if (CollectionsUtil.isNotEmpty(unitItemPoJos)) {
                            accuracy = unitItemPoJos.get(0).getAccuracy();
                        }
                        entity.setProductUnit(entity.getBusinessUnit().toString());
                        entity.setProductNum(Arith.div(entity.getProductNum(), entity.getRate(), accuracy));
                        entity.setWaitInstockNum(Arith.div(entity.getWaitInstockNum(), entity.getRate(), accuracy));
                    }
                    List<WaitOutstockProductPojo> waitOutstockProductPojoList = listOptionPackagePojo.getWaitOutstockProductMap().getOrDefault(entity.getPurchaseSheetId(), new ArrayList<>());
                    WaitOutstockProductPojo waitOutstockProductPojo = new WaitOutstockProductPojo();
                    setProductThumnail(waitOutstockProductPojo, productMap1, entity.getProductId());
                    waitOutstockProductPojo.setProductName(entity.getProductName());
                    waitOutstockProductPojo.setProductNo(entity.getProductNo());
                    setSpecification(waitOutstockProductPojo, productMap1, entity.getProductId());
                    waitOutstockProductPojo.setProductNum(entity.getProductNum());
                    waitOutstockProductPojo.setId(entity.getId());
                    waitOutstockProductPojo.setNum(entity.getWaitInstockNum());
                    waitOutstockProductPojo.setMemo(entity.getMemo());
                    waitOutstockProductPojo.setLinkId(entity.getProductId());
                    String unit = entity.getProductUnit();
                    waitOutstockProductPojo.setUnit(unitItemMap.getOrDefault(unit, ""));
                    // 多单位
                    ProductEntityExt productEntityExt = productMap1.get(entity.getProductId());
                    if (productEntityExt != null) {
                        JSONObject productData = productEntityExt.getData();
                        if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                            Long productUnit = productData.getLong(ProductEnum.UNIT.getAttr());
                            waitOutstockProductPojo.setTransformUnitRate(groupItemsMap.get(productUnit));
                            waitOutstockProductPojo.setEnableMultiUnit(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
                            if (!StringUtil.isDigital(unit) || Long.parseLong(unit) < ProductConstant.MAX_SINGLE_UNIT_VALUE) {
                                MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(productUnit);
                                waitOutstockProductPojo.setUnit(multiUnitItemPoJo != null ? multiUnitItemPoJo.getBaseName() : waitOutstockProductPojo.getUnit());
                            }
                        }
                    }
                    //处理合同维度待入库详情可见权限
                    if (Objects.equals(businessType,XbbRefTypeEnum.PURCHASE.getCode())){
                        ProductEntityExt productEntity = productMap.get(waitOutstockProductPojo.getLinkId());
                        if(Objects.nonNull(productEntity)){
                            parseWaitInstockCanseeData(waitOutstockProductPojo , headListExplain , parseSingleRowDataDTO , productEntity);
                        }
                    }
                    waitOutstockProductPojoList.add(waitOutstockProductPojo);
                    listOptionPackagePojo.getWaitOutstockProductMap().put(entity.getPurchaseSheetId(), waitOutstockProductPojoList);
                }
                break;
            case WAIT_OUTSTOCK:
                optionList.clear();
                parseSingleRowDataDTO = new ParseSingleRowDataDTO();
                List<FieldAttrEntity> contractProductExplains=new ArrayList<>();
                Map<Long,PaasFormDataEntityExt> contractMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                optionList.add(new ButtonPojo(ListOptionTabEnum.OUTSTOCK, XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode()));
                listOptionPackagePojo.setNeedOption9(true);
                List<Long> contractIdList = new ArrayList<>();
                List<ContractProductEntity> contractProductEntityList=new ArrayList<>();
                if (Objects.equals(businessType,XbbRefTypeEnum.PRODUCT.getCode())){
                    contractProductEntityList = formDataListDTO.getContractProductEntityList();
                    for (ContractProductEntity entity : contractProductEntityList) {
                        contractIdList.add(entity.getContractId());
                    }
                    Map<String, Double> productEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    param.put("corpid", corpid);
                    param.put("refIdIn", contractIdList);
                    param.put("type", OutstockTypeEnum.CONTRACT_OUTSTOCK.getCode());
                    param.put("del", 0);
                    param.put("columns","ref_id,product_id,ref_product_id,product_num");
                    param.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                    List<OutstockProductEntity> outstockProductEntityList = outstockProductModel.findEntitys(param);
                    for (OutstockProductEntity entity : outstockProductEntityList){
                        String key;
                        if (Objects.isNull(entity.getRefProductId())){
                            key = entity.getRefId() + "_" + entity.getProductId();
                        }else {
                            key = entity.getRefId() + "_" + entity.getProductId() + "_" + entity.getRefProductId();
                        }
                        Double num = productEntityMap.getOrDefault(key,0D);
                        num += entity.getProductNum();
                        productEntityMap.put(key,num);
                    }
                    Iterator<ContractProductEntity> iterator = contractProductEntityList.iterator();
                    while (iterator.hasNext()) {
                        ContractProductEntity entity = iterator.next();
                        String key = entity.getContractId() + "_" + entity.getProductId() + "_" + entity.getId();
                        //先匹配新数据
                        if (!productEntityMap.containsKey(key)) {
                            //在匹配老数据
                            key = entity.getContractId() + "_" + entity.getProductId();
                            if (!productEntityMap.containsKey(key)) {
                                entity.setWaitOutStockNum(entity.getProductNum());
                                continue;
                            }
                        }
                        Double outstockNum = productEntityMap.get(key);
                        double productNum = entity.getProductNum() == null ? 0D : entity.getProductNum();
                        double leftProductNum = Arith.sub(productNum, outstockNum);
                        if (leftProductNum < 0.00000001 ) {
                            productEntityMap.put(key,0D);
                        } else {
                            productEntityMap.put(key,leftProductNum);
                        }
                        entity.setWaitOutStockNum(productEntityMap.getOrDefault(key,0D));
                    }
                }else if (Objects.equals(businessType , XbbRefTypeEnum.CONTRACT.getCode())) {
                    for (PaasFormDataEntityExt entity : list) {
                        contractIdList.add(entity.getDataId());
                        contractMap.put(entity.getDataId(),entity);
                    }
                    contractProductEntityList = saasHelp.getContractProductWaitOutStock(corpid, contractIdList);
                    //处理用户与团队信息
                    //控制权限
                    PaasFormExplainEntity contractExplainEntity = paasFormExplainModel.getByFormId(formDataListDTO.getFormId(), formDataListDTO.getCorpid());
                    List<FieldAttrEntity> contractExplainList = JSONArray.parseArray(contractExplainEntity.getExplains(), FieldAttrEntity.class);
                    List<FieldAttrEntity> contractProductExplainList = contractExplainList.stream().filter(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.PRODUCT.getAttr())
                    ).collect(Collectors.toList());
                    contractProductExplains = (List<FieldAttrEntity>) contractProductExplainList.get(0).getSubForm().getItems();
                    Map<String, FieldAttrEntity> expalinMap = ExplainUtil.getExplainMapByList(contractProductExplains);
                    UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
                    userAndDepartmentGetDTO.setLoginUser(formDataListDTO.getLoginUser());
                    userAndDepartmentGetDTO.setUserId(formDataListDTO.getUserId());
                    userAndDepartmentGetDTO.setCorpid(corpid);
                    UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
                    Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
                    Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
                    parseSingleRowDataDTO.setExplainMap(expalinMap);
                    parseSingleRowDataDTO.setUserMap(userMap);
                    parseSingleRowDataDTO.setDepartmentMap(departmentMap);
                    parseSingleRowDataDTO.setLoginUser(formDataListDTO.getLoginUser());
                    parseSingleRowDataDTO.setUserId(formDataListDTO.getUserId());
                    parseSingleRowDataDTO.setCorpid(corpid);
                }
                Set<Long> productIdSet2 = new HashSet<>();
                for (ContractProductEntity entity : contractProductEntityList) {
                    productIdSet2.add(entity.getProductId());
                }
                Map<Long, ProductEntityExt> productMap2 = getProductMap(productIdSet2, corpid);
                groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
                groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
                productItems = relativeProductHelp.getBusinessUnitItems(corpid);
                productItems.forEach(item -> unitItemMap.put(item.getValue().toString(), item.getText()));
                for (ContractProductEntity entity : contractProductEntityList) {
                    if (Objects.nonNull(entity.getBusinessUnit())) {
                        entity.setProductUnit(entity.getBusinessUnit().toString());
                        entity.setProductNum(Arith.div(entity.getProductNum(), entity.getRate()));
                        entity.setWaitOutStockNum(Arith.div(entity.getWaitOutStockNum(), entity.getRate()));
                    }
                    List<WaitOutstockProductPojo> waitOutstockProductPojoList = listOptionPackagePojo.getWaitOutstockProductMap().getOrDefault(entity.getContractId(), new ArrayList<>());
                    Double stock=BasicConstant.ZERO_DOUBLE;
                    if(productMap2.get(entity.getProductId())!=null){
                        JSONObject productData=productMap2.get(entity.getProductId()).getData();
                        stock=productData.getDouble(ProductEnum.STOCK.getAttr());
                    }
                    WaitOutstockProductPojo waitOutstockProductPojo = new WaitOutstockProductPojo();
                    setProductThumnail(waitOutstockProductPojo, productMap2, entity.getProductId());
                    waitOutstockProductPojo.setProductName(entity.getProductName());
                    waitOutstockProductPojo.setProductNo(entity.getProductNo());
                    setSpecification(waitOutstockProductPojo, productMap2, entity.getProductId());
                    waitOutstockProductPojo.setProductNum(entity.getProductNum());
                    String unit = entity.getProductUnit();
                    waitOutstockProductPojo.setId(entity.getId());
                    waitOutstockProductPojo.setNum(entity.getWaitOutStockNum());
                    waitOutstockProductPojo.setMemo(entity.getMemo());
                    waitOutstockProductPojo.setStock(stock);
                    waitOutstockProductPojo.setUnit(unitItemMap.getOrDefault(unit, ""));
                    // 多单位
                    ProductEntityExt productEntityExt = productMap2.get(entity.getProductId());
                    if (productEntityExt != null) {
                        JSONObject productData = productEntityExt.getData();
                        if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                            Long productUnit = productData.getLong(ProductEnum.UNIT.getAttr());
                            waitOutstockProductPojo.setTransformUnitRate(groupItemsMap.get(productUnit));
                            waitOutstockProductPojo.setEnableMultiUnit(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
                            if (!StringUtil.isDigital(unit) || Long.parseLong(unit) < ProductConstant.MAX_SINGLE_UNIT_VALUE) {
                                MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(productUnit);
                                waitOutstockProductPojo.setUnit(multiUnitItemPoJo != null ? multiUnitItemPoJo.getBaseName() : waitOutstockProductPojo.getUnit());
                            }
                        }
                    }
                    //处理合同维度待入库详情可见权限
                    if (Objects.equals(businessType,XbbRefTypeEnum.CONTRACT.getCode())){
                        PaasFormDataEntityExt contract=contractMap.get(entity.getContractId());
                        parseWaitOutStockCanseeData(waitOutstockProductPojo , contractProductExplains , parseSingleRowDataDTO ,contract);
                    }
                    waitOutstockProductPojoList.add(waitOutstockProductPojo);
                    listOptionPackagePojo.getWaitOutstockProductMap().put(entity.getContractId(), waitOutstockProductPojoList);
                }
                break;
            case PRODUCTION_ORDER:
//                optionList.add(new ButtonPojo(ListOptionTabEnum.FINISH));
                listOptionPackagePojo.setProductionOrderFinish(true);
                break;
            case PAYMENT_SHEET:
                if (!Objects.equals(ModelTypeEnum.INVOICE.getCode(), currentModelType) && !Objects.equals(Long.valueOf(ListGroupEnum.APPROVAL.getCode()), formDataListDTO.getListGroupId())) {
                    //非开票模式才可能有新建发票按钮
                    optionList.add(new ButtonPojo(ListOptionTabEnum.ADDINVOICE, XbbRefTypeEnum.INVOICE.getCode(), distributorMark));
                }
                //paymentCheckInvoiceOption(formDataListDTO,list,listOptionPackagePojo,XbbRefTypeEnum.PAYMENT_SHEET);
                checkInvoiceOption(formDataListDTO,list,listOptionPackagePojo,XbbRefTypeEnum.PAYMENT_SHEET);
                break;
            case PAY_SHEET:
                if (!Objects.equals(Long.valueOf(ListGroupEnum.APPROVAL.getCode()), formDataListDTO.getListGroupId())) {
                    optionList.add(new ButtonPojo(ListOptionTabEnum.ADDPURCHASEINVOICE, XbbRefTypeEnum.PURCHASE_INVOICE.getCode()));
                }
                checkInvoiceOption(formDataListDTO,list,listOptionPackagePojo,XbbRefTypeEnum.PAY_SHEET);
                break;
            case CREDIT_LIMIT:
                listOptionPackagePojo.setFreeze(true);
                break;
            case CREDIT_TEMPORARY_LIMIT:
                listOptionPackagePojo.setRevoke(true);
                break;
            case CUSTOMER_STATEMENT_STATISTIC:
                listOptionPackagePojo.setStatement(true);
                for (FieldAttrEntity fieldAttrEntity : formDataEsListVO.getHeadList()) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), CustomerStatementStatisticEnum.STATEMENT_NO.getAttr())) {
                        fieldAttrEntity.setTagAttr(CustomerStatementStatisticEnum.STATEMENT_NO.getAttr() + "Tag");
                    }
                }
                listOptionPackagePojo.setArchivedTag(CustomerStatementStatisticEnum.STATEMENT_NO.getAttr() + "Tag");
                break;
            case ALL_CLUE:
                //跟进
                listOptionPackagePojo.setNeedOption4(formDataListDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.CUSTOMER_COMMUNICATE_VIEW.getAlias()));
                getClueCommunicate(formDataListDTO, corpid, listOptionPackagePojo, dataIdList);
                //提醒
                listOptionPackagePojo.setNeedOption2(true);
                getPushNotify(dataIdList, corpid, businessType, listOptionPackagePojo.getPushNotifyList());
                // 判断是否有呼叫权限
                boolean isClueActiveCall = callCenterCommonService.isOpenCallAndAgent(corpid, userId);
                // 判断是否有阿里云呼叫中心权限
                isActiveAliyunCall = callCenterCommonService.isActiveAliyunCall(corpid,userId).IsActiveAliyunAndHasRole();
                if (isClueActiveCall||isActiveAliyunCall) {
                    listOptionPackagePojo.setNeedOption3(true);
                }
                //标签
                listOptionPackagePojo.setArchivedTag(ClueEnum.COMPANY_NAME.getAttr() + "Tag");
                listOptionPackagePojo.setPublicTag(ClueEnum.COMPANY_NAME.getAttr()  + "Tag");
                listOptionPackagePojo.setPublicTagMap(tagLinkModel.getCluePublicTag(corpid, dataIdList));
                for (FieldAttrEntity fieldAttrEntity : formDataEsListVO.getHeadList()) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), ClueEnum.COMPANY_NAME.getAttr())) {
                        fieldAttrEntity.setTagAttr(ClueEnum.COMPANY_NAME.getAttr() + "Tag");
                        break;
                    }
                }
                break;
            case CLUE_PUBLIC:
                // 判断是否有阿里云呼叫中心权限
                isActiveAliyunCall = callCenterCommonService.isActiveAliyunCall(corpid,userId).IsActiveAliyunAndHasRole();
                if (isActiveAliyunCall) {
                    listOptionPackagePojo.setNeedOption3(true);
                }
                //跟进
                listOptionPackagePojo.setNeedOption4(true);
                getClueCommunicate(formDataListDTO, corpid, listOptionPackagePojo, dataIdList);
                if (permSet.contains(ProPermissionAliasEnum.CLUE_GAIN.getAlias())) {
                    optionList.add(new ButtonPojo(ListOptionTabEnum.GRAB));
                }
                // ‘归’标签
                listOptionPackagePojo.setArchivedTag(ClueEnum.COMPANY_NAME.getAttr() + "Tag");
                for (FieldAttrEntity fieldAttrEntity : formDataEsListVO.getHeadList()) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), ClueEnum.COMPANY_NAME.getAttr())) {
                        fieldAttrEntity.setTagAttr(ClueEnum.COMPANY_NAME.getAttr() + "Tag");
                        break;
                    }
                }
                // ‘转移’标签
                listOptionPackagePojo.setTransferTag(ClueEnum.COMPANY_NAME.getAttr() + "Tag");
                for (FieldAttrEntity fieldAttrEntity : formDataEsListVO.getHeadList()) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), ClueEnum.COMPANY_NAME.getAttr())) {
                        fieldAttrEntity.setTagAttr(ClueEnum.COMPANY_NAME.getAttr() + "Tag");
                        break;
                    }
                }
                listOptionPackagePojo.setTransferTagMap(tagLinkModel.getTransferTag(corpid, dataIdList,XbbRefTypeEnum.CLUE_TRANSFER.getCode()));
                break;
            case CLUE_RECYCLE:
                optionList.clear();
                // 判断是否有阿里云呼叫中心权限
                isActiveAliyunCall = callCenterCommonService.isActiveAliyunCall(corpid,userId).IsActiveAliyunAndHasRole();
                if (isActiveAliyunCall) {
                    listOptionPackagePojo.setNeedOption3(true);
                }
            default:
                break;
        }
        return listOptionPackagePojo;
    }

    public void getCommunicate(FormDataListDTO formDataListDTO, String corpid, ListOptionPackagePojo listOptionPackagePojo, List<Long> dataIdList) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery("data." + CustomerCommunicateEnum.CUSTOMER_NAME.getAttr()+".keyword", dataIdList));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termQuery("logType", 0));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE.getType()));
        //加上数据权限的判断
        if (!Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), formDataListDTO.getDistributorMark())) {
            detailTabDataPermissionHelp.specialListCustomerCommunicate(formDataListDTO, boolQueryBuilder);
        }
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.collapse(new CollapseBuilder("data.text_1.keyword"));
        sourceBuilder.query(boolQueryBuilder);
        //限定返回值
        sourceBuilder.fetchSource("data.text_1",null);
        //分页
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, dataIdList.size());
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE.getIndex());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest, PaasFormDataEntityExt.class);
        if(esEntities != null){
            List<Long> communicateList = new ArrayList<>();
            List<PaasFormDataEntityExt> resultList = new ArrayList<>(esEntities.getContent());
            for (PaasFormDataEntityExt paasFormDataEntityExt : resultList) {
                JSONObject data = paasFormDataEntityExt.getData();
                if (Objects.nonNull(data) && Objects.nonNull(data.getLong(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr()))) {
                    communicateList.add(data.getLong(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr()));
                }
            }
            listOptionPackagePojo.setCommunicateList(communicateList);
        }
    }

    public void getClueCommunicate(FormDataListDTO formDataListDTO, String corpid, ListOptionPackagePojo listOptionPackagePojo, List<Long> dataIdList) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery(CustomerCommunicateEnum.getEsAttr4Keyword(CustomerCommunicateEnum.COMMUNICATE_BUSINESS), dataIdList));
        boolQueryBuilder.filter(termQuery(CustomerCommunicateEnum.getEsAttr4Keyword(CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE), XbbRefTypeEnum.CLUE.getCode()));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termQuery("logType", 0));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE.getType()));
        //加上数据权限的判断
        if (!Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), formDataListDTO.getDistributorMark())) {
            detailTabDataPermissionHelp.specialListCustomerCommunicate(formDataListDTO, boolQueryBuilder);
        }
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.collapse(new CollapseBuilder(CustomerCommunicateEnum.getEsAttr4Keyword(CustomerCommunicateEnum.COMMUNICATE_BUSINESS)));
        sourceBuilder.query(boolQueryBuilder);
        //限定返回值
        sourceBuilder.fetchSource(CustomerCommunicateEnum.getAttrConnectData(CustomerCommunicateEnum.COMMUNICATE_BUSINESS),null);
        //分页
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, dataIdList.size());
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE.getIndex());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest, PaasFormDataEntityExt.class);
        if(esEntities != null){
            List<Long> communicateList = new ArrayList<>();
            List<PaasFormDataEntityExt> resultList = new ArrayList<>(esEntities.getContent());
            for (PaasFormDataEntityExt paasFormDataEntityExt : resultList) {
                JSONObject data = paasFormDataEntityExt.getData();
                if (Objects.nonNull(data) && Objects.nonNull(data.getLong(CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr()))) {
                    communicateList.add(data.getLong(CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr()));
                }
            }
            listOptionPackagePojo.setCommunicateList(communicateList);
        }
    }

    public void setSpecification(WaitOutstockProductPojo waitOutstockProductPojo,
                                  Map<Long, ProductEntityExt> productMap, Long productId) {
        ProductEntityExt productEntityExt = productMap.get(productId);
        String specification = "";
        if (productEntityExt != null) {
            JSONObject productData = productEntityExt.getData();
            specification = specificationModel.joinSpecification(productData.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()));
        }
        waitOutstockProductPojo.setSpecification(specification);
    }

    public void setProductThumnail(WaitOutstockProductPojo waitOutstockProductPojo,
                                    Map<Long, ProductEntityExt> productMap, Long productId) {
        JSONArray thumbnail = new JSONArray();
        ProductEntityExt productEntityExt = productMap.get(productId);
        if (productEntityExt != null) {
            JSONArray productImgs = new JSONArray();
            try {
                JSONObject data = productEntityExt.getData();
                if (Objects.nonNull(data) && CollectionsUtil.isEmpty(data.getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr()))) {
                    data.put(ProductEnum.PRODUCT_IMGS.getAttr(), data.getJSONArray(ProductEnum.THUMBNAIL.getAttr()));
                }
                productImgs = productEntityExt.getData().getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr());
            } catch (Exception e) {

            }
            if (productImgs != null && !productImgs.isEmpty()) {
                thumbnail.add(productImgs.getString(0));
            }
        }
        waitOutstockProductPojo.setProductThumnail(thumbnail);
    }

    public Map<Long, ProductEntityExt> getProductMap(Set<Long> productIdSet, String corpid) {
        return productModel.getProductMapByIdIn(corpid, new ArrayList<>(productIdSet), BasicConstant.ZERO);
    }

    private Map<String, String> getUnitMap(String corpid) throws XbbException {
        PaasFormEntityExt paasForm = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        Map<String,String> unitMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (paasForm != null) {
            unitMap = dataDictionaryModel.getDictionaryMap4Saas(DictionaryEnum.PRODUCT_UNIT,
                    corpid,paasForm.getId());
        }
        return unitMap;
    }


    private ListOptionPackagePojo setOptionBase(List<Long> dataIdList, FormDataListDTO formDataListDTO) {
        ListOptionPackagePojo listOptionPackagePojo = new ListOptionPackagePojo();
        listOptionPackagePojo.setEmergencyTag(WorkOrderEnum.SHEET_NO.getAttr() + "Tag");
        return listOptionPackagePojo;
    }

    /**
     * 获取提醒
     *
     * @param dataIdList
     * @param corpid
     * @param businessType
     * @param pushNotifyList
     */
    public void getPushNotify(List<Long> dataIdList, String corpid, Integer businessType, List<Long> pushNotifyList) {
        pushModel.getPushNotify(dataIdList, corpid, businessType, pushNotifyList);
    }

    /**
     * 特殊列表页表头
     *
     * @param businessType
     * @param subBusinessType
     * @return
     */
    private List<JSONObject> getTableHead(Integer businessType, Integer subBusinessType) {
        if (Objects.equals(XbbRefTypeEnum.WAIT_PURCHASE.getCode(), subBusinessType)) {
            if (Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(), businessType)) {
                List<JSONObject> waitTabHead = new ArrayList<>(ProductEnum.getWaitTabHeadd());
                waitTabHead.remove(0);
                return waitTabHead;
            } else {
                return ContractEnum.getWaitTabHeadd();
            }
        } else if (Objects.equals(XbbRefTypeEnum.WAIT_OUTSTOCK.getCode(), subBusinessType) || Objects.equals(XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode(), subBusinessType)) {
            return ProductEnum.getWaitStockTabHeadd(subBusinessType);
        } else if (Objects.equals(XbbRefTypeEnum.WAIT_PRODUCE.getCode(), subBusinessType)) {
            if (Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(), businessType)) {
                List<JSONObject> waitTabHead = new ArrayList<>(ProductEnum.getWaitTabHeadd());
                waitTabHead.remove(1);
                return waitTabHead;
            } else {
                return ContractEnum.getWaitTabHeadd();
            }
        }
        return new ArrayList<>();
    }

    /**
     * 根据业务类型获取options表头，并且根据解释的可见性进行过滤
     *
     * @param businessType
     * @return 可见的options表头数组
     * @author chaoxiong.lei
     * @Date 22:25 2019/3/11
     * @since v1.0
     **/
    public JSONArray packageOptionTableHead(String userId,Integer businessType, Long listGroupId, RelativeProductExplainVO relativeProductExplainVO) {
        if (Objects.equals(businessType, XbbRefTypeEnum.STOCK_SEARCH.getCode())) {
            if (Objects.equals(listGroupId, ListGroupEnum.WARNING_SEARCH.getCode().longValue())) {
                businessType = XbbRefTypeEnum.WARNING_SEARCH.getCode();
            } else if (Objects.equals(listGroupId, ListGroupEnum.GUARANTEE_SEARCH.getCode().longValue())) {
                businessType = XbbRefTypeEnum.GUARANTEE_SEARCH.getCode();
            }
        }
        // 拼装解释
        List<SubOptionTableHeadEnum> optionTableHeadEnums = OptionTableHeadEnum.getListByBusinessType(businessType);

        // saasAddHelp.getRelativeProductExplainsFromDB(corpid, nowProductExplainMap, nowStockProductExplainMap);
        Map<String, FieldAttrEntity> nowProductExplainMap = relativeProductExplainVO.getNowProductExplainMap();
        Map<String, FieldAttrEntity> nowStockProductExplainMap = relativeProductExplainVO.getNowStockProductExplainMap();

        JSONArray tableHeadArray = new JSONArray();
        if (optionTableHeadEnums != null) {
            for (SubOptionTableHeadEnum item : optionTableHeadEnums) {
                String saasAttr = item.getSaasAttr();
                if (saasAttr != null) {
                    if (nowProductExplainMap != null && nowProductExplainMap.containsKey(saasAttr)) {
                        FieldAttrEntity productFieldAttrEntity = nowProductExplainMap.get(saasAttr);
                        Integer visible = productFieldAttrEntity.getVisible();
                        Integer isOpen = productFieldAttrEntity.getIsOpen();
                        Integer visibleScopeEnable = productFieldAttrEntity.getVisibleScopeEnable();
                        if (Objects.equals(visible, 1) && Objects.equals(visibleScopeEnable, 1) && Objects.nonNull(productFieldAttrEntity.getVisibleScopeRule())) {
                            if (CollectionsUtil.isNotEmpty(productFieldAttrEntity.getVisibleScopeRule().getUser()) && Objects.equals(productFieldAttrEntity.getVisibleScopeRule().getType(), 1) && productFieldAttrEntity.getVisibleScopeRule().getUser().contains(userId)) {
                                // 高级不可见
                                continue;
                            }
                        }
                        if ( !Objects.equals(visible, 1) || !Objects.equals(isOpen, 1)) {
                            // 不可见
                            continue;
                        }
                    }
                    if (Objects.equals(item, SubOptionTableHeadEnum.PRODUCT_COST_TOTAL)) {
                        if (nowProductExplainMap != null && nowProductExplainMap.containsKey(SubOptionTableHeadEnum.PRODUCT_COST.getSaasAttr())) {
                            Integer visible = nowProductExplainMap.get(SubOptionTableHeadEnum.PRODUCT_COST.getSaasAttr()).getVisible();
                            Integer isOpen = nowProductExplainMap.get(SubOptionTableHeadEnum.PRODUCT_COST.getSaasAttr()).getIsOpen();
                            if (!Objects.equals(visible, 1) || !Objects.equals(isOpen, 1)) {
                                // 不可见
                                continue;
                            }
                        }
                    }
                    if (nowStockProductExplainMap != null && nowStockProductExplainMap.containsKey(saasAttr)) {
                        Integer visible = nowStockProductExplainMap.get(saasAttr).getVisible();
                        Integer isOpen = nowStockProductExplainMap.get(saasAttr).getIsOpen();
                        if (!Objects.equals(visible, 1) || !Objects.equals(isOpen, 1)) {
                            // 不可见
                            continue;
                        }
                    }
                }
                // saasAttr为null或者解释中不包含的，为必须显示的
                JSONObject tablHeadObj = new JSONObject();
                tablHeadObj.put(StringConstant.PROP, item.getProp());
                tablHeadObj.put(StringConstant.LABEL, item.getLabel());
                tablHeadObj.put(StringConstant.NUM_TIGHT, BasicConstant.ZERO);
                if(Objects.equals(item, SubOptionTableHeadEnum.PRODUCT_COST) || Objects.equals(item, SubOptionTableHeadEnum.PRODUCT_STOCK) || Objects.equals(item, SubOptionTableHeadEnum.PRODUCT_PRICE) ||
                        Objects.equals(item, SubOptionTableHeadEnum.WARNING_UPPER_LIMIT)|| Objects.equals(item, SubOptionTableHeadEnum.WARNING_LOWER_LIMIT) || Objects.equals(item, SubOptionTableHeadEnum.GUARANTEE_PERIOD) ||
                        Objects.equals(item, SubOptionTableHeadEnum.PRODUCT_NUM) || Objects.equals(item, SubOptionTableHeadEnum.PRODUCT_COST_TOTAL)){
                    tablHeadObj.put(StringConstant.NUM_TIGHT, BasicConstant.ONE);
                }
                if (saasAttr != null) {
                    if (nowProductExplainMap != null && nowProductExplainMap.containsKey(saasAttr)) {
                        tablHeadObj.put(StringConstant.LABEL, nowProductExplainMap.get(saasAttr).getAttrName());
                    }
                }
                tableHeadArray.add(tablHeadObj);
            }
        }
        return tableHeadArray;
    }

    public void tempData4Show(FormDataListDTO formDataListDTO, PaasFormDataEsListVO formDataListVO) throws XbbException {
        String corpid = formDataListDTO.getCorpid();
        Integer businessType = formDataListDTO.getBusinessType();
        Integer subBusinessType = formDataListDTO.getSubBusinessType();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        List<Long> dataIdList = new ArrayList<>();
        formDataListVO.getPaasFormDataESList().forEach(item -> dataIdList.add(item.getDataId()));

        switch (xbbRefTypeEnum) {
            case CUSTOMER_MANAGEMENT:
//                if (Objects.equals(formDataListDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())){
//                    return;
//                }
                Map<String, FieldAttrEntity> explainMap = new HashMap<>(formDataListVO.getHeadList().size());
                for (FieldAttrEntity item : formDataListVO.getHeadList()) {
                    explainMap.put(item.getAttr(), item);
                }
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword", formDataListDTO.getCorpid()));
                boolQueryBuilder.filter(termQuery("del", 0));
                boolQueryBuilder.filter(termsQuery(ContactEnum.getEsAttr4Keyword(ContactEnum.CUSTOMER_NAME), dataIdList));
                boolQueryBuilder.filter(termQuery("data." + ContactEnum.IS_MAIN.getAttr(), 1));
                boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_CONTACT.getType()));
                sourceBuilder.query(boolQueryBuilder);
                Integer pageSize = dataIdList.size() == 0 ? 1 : dataIdList.size() * 2;
                PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, pageSize);
                SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTACT.getIndex());
                searchRequest.source(sourceBuilder);
                XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest, PaasFormDataEntityExt.class);
                List<PaasFormDataEntityExt> contactList = esEntities.getContent();
                Map<Long, Object> nameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<Long, Object> phoneMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (PaasFormDataEntityExt entity : contactList) {
                    nameMap.put(entity.getData().getLong(ContactEnum.CUSTOMER_NAME.getAttr()), entity.getData().get(ContactEnum.NAME.getAttr()));
                    phoneMap.put(entity.getData().getLong(ContactEnum.CUSTOMER_NAME.getAttr()), entity.getData().get(ContactEnum.PHONE.getAttr()));
                }
                PaasFormExplainEntity contactExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.CONTACT.getCode(), corpid);
                Map<String, FieldAttrEntity> contactExplainMap = ExplainUtil.getExplainMap(contactExplain.getExplains(), ContactEnum.PHONE.getAttr());
                Integer showPublicPool = 0;
                Integer publicPool = 0;
                if (Objects.nonNull(contactExplainMap.get(ContactEnum.PHONE.getAttr()))) {
                    FieldAttrEntity phoneAttr = contactExplainMap.get(ContactEnum.PHONE.getAttr());
                    showPublicPool = phoneAttr.getShowPublicPool();
                    publicPool = phoneAttr.getPublicPool();
                    List<FieldAttrEntity> headList = formDataListVO.getHeadList();
                    headList.forEach(item -> {
                        if (Objects.equals(item.getAttr(), CustomerManagementEnum.CONTACT_PHONE.getAttr()) && Objects.equals(item.getIsRedundant(), 0)) {
                            //20177 【成功部】联系人联系方式类型修改后，主联系人类型没有同步
                            item.setSubForm(phoneAttr.getSubForm());
                        }
                    });
                }

                FieldAttrEntity contactName = explainMap.get(CustomerManagementEnum.CONTACT_NAME.getAttr());
                FieldAttrEntity contactPhone = explainMap.get(CustomerManagementEnum.CONTACT_PHONE.getAttr());
                FieldAttrEntity customerPhone = explainMap.get(CustomerManagementEnum.PHONE.getAttr());
                Integer customerShowPublicPool = 0;
                Integer customerPublicPool = 0;
                if (Objects.nonNull(customerPhone)) {
                    customerShowPublicPool = customerPhone.getShowPublicPool();
                    customerPublicPool = customerPhone.getPublicPool();
                }

                Boolean systemContactName = Objects.nonNull(contactName) && Objects.equals(contactName.getIsRedundant(), 0);
                Boolean systemContactPhone = Objects.nonNull(contactPhone) && Objects.equals(contactPhone.getIsRedundant(), 0);
                for (PaasFormDataEntityExt entity : formDataListVO.getPaasFormDataESList()) {
                    Integer isPublic = getIntegerOrDefaultFromFormData(entity.getData(), CustomerManagementEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
                    // 系统字段才去解析
                    if (systemContactName) {
                        entity.getData().put(CustomerManagementEnum.CONTACT_NAME.getAttr(), nameMap.getOrDefault(entity.getDataId(), ""));
                    }
                    // 系统字段才去解析
                    if (systemContactPhone) {
                        if (Objects.equals(isPublic, BasicConstant.ONE) && Objects.equals(showPublicPool, BasicConstant.ONE) && Objects.equals(publicPool, BasicConstant.ZERO)) {
                            // 如果联系人模板电话字段配置了公海池不可见，那么公海客户的主联系人电话不可见
                            entity.getData().put(CustomerManagementEnum.CONTACT_PHONE.getAttr(), new JSONArray());
                        } else {
//                            if (!Objects.equals(formDataListDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())){
                                entity.getData().put(CustomerManagementEnum.CONTACT_PHONE.getAttr(), phoneMap.getOrDefault(entity.getDataId(), new JSONArray()));
//                            }
                        }
                    }
                    if (Objects.equals(isPublic, BasicConstant.ONE) && Objects.equals(customerShowPublicPool, BasicConstant.ONE) && Objects.equals(customerPublicPool, BasicConstant.ZERO)) {
                        // 如果客户模板电话字段配置了公海池不可见，那么公海客户的电话不可见
                        entity.getData().put(CustomerManagementEnum.PHONE.getAttr(), new JSONArray());
                    }
                }
                break;
            case CLUE:
                Map<String, FieldAttrEntity> explainEntityMap = formDataListDTO.getExplainMap();
                FieldAttrEntity cluePhone = explainEntityMap.get(ClueEnum.PHONE.getAttr());
                Integer clueShowPublicPool = 0;
                Integer cluePublicPool = 0;
                if (Objects.nonNull(cluePhone)) {
                    clueShowPublicPool = cluePhone.getShowPublicPool();
                    cluePublicPool = cluePhone.getPublicPool();
                }
                for (PaasFormDataEntityExt entity : formDataListVO.getPaasFormDataESList()) {
                    Integer isPublic = getIntegerOrDefaultFromFormData(entity.getData(), ClueEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
                    if (Objects.equals(isPublic, BasicConstant.ONE) && Objects.equals(clueShowPublicPool, BasicConstant.ONE) && Objects.equals(cluePublicPool, BasicConstant.ZERO)) {
                        // 如果模板电话字段配置了公海池不可见，那么公海线索的电话不可见
                        entity.getData().put(ClueEnum.PHONE.getAttr(), new JSONArray());
                    }
                }
                break;
            case PAYMENT:
                for (PaasFormDataEntityExt entity : formDataListVO.getPaasFormDataESList()) {
                    JSONObject data = entity.getData();
                    Integer isRed = FastJsonHelper.getIntegerOrDefaultFromFormData(data, PaymentEnum.RECEIVABLE_IS_RED.getAttr(), BasicConstant.ZERO);
                    if (Objects.equals(isRed, BasicConstant.ONE)) {
                        // 红冲回款单，列表页数据变成红色，和前端约定用isRed为1控制
                        data.put("isRed", BasicConstant.ONE);
                    }
                }
                break;
            case PAYMENT_SHEET:
                for (PaasFormDataEntityExt entity : formDataListVO.getPaasFormDataESList()) {
                    JSONObject data = entity.getData();
                    String type = data.getString(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr());
                    if (PaymentSheetTypeEnum.isRed(type)) {
                        data.put("isRed", BasicConstant.ONE);
                    }
                }
                break;
            case PAY_SHEET:
                for (PaasFormDataEntityExt entity : formDataListVO.getPaasFormDataESList()) {
                    JSONObject data = entity.getData();
                    String type = data.getString(PaySheetEnum.PAY_SHEET_TYPE.getAttr());
                    if (PaySheetTypeEnum.isRed(type)) {
                        data.put("isRed", BasicConstant.ONE);
                    }
                }
                break;
            case RETURNED_PURCHASE:
                for (PaasFormDataEntityExt entity : formDataListVO.getPaasFormDataESList()) {
                    JSONObject data = entity.getData();
                    Long outStockId = FastJsonHelper.getLongOrDefaultFromFormData(data, ReturnedPurchaseEnum.OUTSTOCK_ID.getAttr(), 0L);
                    Integer status = outStockId  <= 0 ? ReturnedPurchaseStatusEnum.WAIT_OUTSTOCK.getStatus() : ReturnedPurchaseStatusEnum.OUTSTOCK.getStatus();
                    data.put(ReturnedPurchaseEnum.STATUS.getAttr(), status);
                }
                break;
            case PRODUCT:
                if (Objects.equals(subBusinessType, XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())){
                    List<String> warehouseIdList = new ArrayList<>();
                    formDataListVO.getPaasFormDataESList().forEach(item -> {
                        if (item.getData().containsKey(ProductEnum.WAREHOUSE.getAttr())) {
                            List<String> idList = JsonHelperUtil.parseArray(item.getData().getString(ProductEnum.WAREHOUSE.getAttr()), String.class);
                            warehouseIdList.addAll(idList);
                        }
                    });
                    if (warehouseIdList.isEmpty()){
                        return;
                    }
                    //去除warehouseIdList里面的空值，防止查询报错
                    warehouseIdList.removeIf(item -> Objects.isNull(item) || "null".equals(item));
                    boolQueryBuilder = boolQuery();
                    boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                    boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
                    boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(),warehouseIdList));
                    List<PaasFormDataEntityExt> warehouseList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_WAREHOUSE,boolQueryBuilder,PaasFormDataEntityExt.class,Arrays.asList(FieldTypeEnum.DATAID.getAlias(),WarehouseEnum.getAttrConnectData(WarehouseEnum.WAREHOUSE_NAME)));
                    Map<Long,String> warehouseNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    warehouseList.forEach(item -> warehouseNameMap.put(item.getDataId(),item.getData().getString(WarehouseEnum.WAREHOUSE_NAME.getAttr())));
                    for (PaasFormDataEntityExt entityExt : formDataListVO.getPaasFormDataESList()){
                        JSONArray idList = entityExt.getData().getJSONArray(ProductEnum.WAREHOUSE.getAttr());
                        if (Objects.isNull(idList) || idList.isEmpty()){
                            continue;
                        }
                        List<String> nameList = new ArrayList<>();
                        for (int i=0;i<idList.size();i++){
                            Long id = idList.getLong(i);
                            nameList.add(warehouseNameMap.getOrDefault(id,""));
                        }
                        entityExt.getData().put(ProductEnum.WAREHOUSE_LINK_TEXT.getAttr(),nameList);
                    }
                }
                break;
            case OTHER_INCOME:
                for (PaasFormDataEntityExt entity : formDataListVO.getPaasFormDataESList()) {
                    JSONObject data = entity.getData();
                    String type = data.getString(OtherIncomeEnum.SHEET_TYPE_OTHER.getAttr());
                    if (OtherIncomeSheetTypeEnum.isRed(type)) {
                        data.put("isRed", BasicConstant.ONE);
                    }
                }
                break;
            case OTHER_EXPENSE:
                for (PaasFormDataEntityExt entity : formDataListVO.getPaasFormDataESList()) {
                    JSONObject data = entity.getData();
                    String type = data.getString(OtherExpenseEnum.SHEET_TYPE_OTHER.getAttr());
                    if (OtherExpenseSheetTypeEnum.isRed(type)) {
                        data.put("isRed", BasicConstant.ONE);
                    }
                }
                break;
            default:
                break;
        }
    }

    public void handleEsData4Show(FormDataListDTO formDataListDTO, PaasFormDataEsListVO formDataListVO) throws XbbException {
        String corpid = formDataListDTO.getCorpid();
        Integer businessType = formDataListDTO.getBusinessType();
        Integer subBusinessType = formDataListDTO.getSubBusinessType();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        List<Long> dataIdList = new ArrayList<>();
        for (PaasFormDataEntityExt entity : formDataListVO.getPaasFormDataESList()){
            dataIdList.add(entity.getDataId());
        }
        List<PaasFormDataEntityExt> dataList = formDataListVO.getPaasFormDataESList();
        switch (xbbRefTypeEnum) {
            case PRODUCT:
                if (Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_PURCHASE.getCode()) || Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_PRODUCE.getCode())){
                    formDataListVO.getPaasFormDataESList().forEach(paasFormDataEntityExt -> {
                        paasFormDataEntityExt.setParentId(paasFormDataEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr()));
                    });
                    productService.setChildSpecification(formDataListVO.getPaasFormDataESList(),corpid);
                }
                if (Objects.equals(subBusinessType, XbbRefTypeEnum.STOCK_SEARCH.getCode()) || Objects.equals(subBusinessType, XbbRefTypeEnum.WARNING_SEARCH.getCode()) || Objects.equals(subBusinessType,XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                    // 库存查询
                    productService.setChildSpecification(formDataListVO.getPaasFormDataESList(),corpid);
                    productService.setProductSupplier(formDataListVO, corpid, dataIdList);
                } else {
                    FilterAttrOnOffJXCDTO filterAttrOnOffJXCDTO = new FilterAttrOnOffJXCDTO();
                    BeanUtil.copyProperties(formDataListDTO, filterAttrOnOffJXCDTO);
                    filterAttrOnOffJXCDTO.setFieldAttrEntityList(formDataListVO.getHeadList());
                    filterAttrOnOffJXCDTO.setOperatePageCode(OperatePageEnum.LIST.getCode());
                    productModel.filterAttrOnOffJXC(filterAttrOnOffJXCDTO);
                    boolean isSpuList = Objects.equals(formDataListDTO.getSubBusinessType(),XbbRefTypeEnum.PRODUCT.getCode());
                    if (isSpuList){
                        productService.setProductSupplierAndWarehouse(formDataListVO, corpid, dataIdList,isSpuList);
                    } else {
                        // 选择产品界面不需要渲染供应商，故去除
                        if (!Objects.equals(formDataListDTO.getSubBusinessType(), XbbRefTypeEnum.SELECT_PRODUCT.getCode())) {
                            if (!Objects.equals(formDataListDTO.getSubBusinessType(), XbbRefTypeEnum.WAIT_OUTSTOCK.getCode())){
                                List<Long> parentDataIdList = new ArrayList<>();
                                formDataListVO.getPaasFormDataESList().forEach(item -> parentDataIdList.add(item.getDataId()));
                                productService.setProductSupplierAndWarehouse(formDataListVO, corpid, parentDataIdList,isSpuList);
                            }
                        }
                    }
                }
                break;
            case CONTRACT:
            case REFUND:
            case RETURN:
            case SALES_OPPORTUNITY:
            case PURCHASE:
            case RETURNED_PURCHASE:
            case ASSEMBLE:
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case INVENTORY:
            case TRANSFER:
            case QUOTATION:
            case BOM_BILL:
            case PRODUCTION_ORDER:
            case COST_ADJUST:
                if (dataIdList.isEmpty()){
                    return;
                }
                Map<String,List<FieldAttrEntity>> keyListMap = analysisListProductData(dataList,dataIdList,businessType,corpid,1,null, formDataListDTO);
                if (!keyListMap.isEmpty()){
                    for (FieldAttrEntity fieldAttrEntity : formDataListVO.getHeadList()) {
                        if (keyListMap.containsKey(fieldAttrEntity.getAttr())){
                            int index = 0;
                            int productIndex = -1;
                            List<FieldAttrEntity> subExplainList = (List<FieldAttrEntity>) fieldAttrEntity.getSubForm().getItems();
                            for (FieldAttrEntity field : subExplainList) {
                                if (Objects.equals(field.getAttr(),SelectProductEnum.PRODUCT.getAttr())){
                                    productIndex = index;
                                    break;
                                }
                                index++;
                            }
                            if (productIndex >= 0){
                                if (Objects.equals(fieldAttrEntity.getSubForm().getItems().size(),productIndex)) {
                                    subExplainList.addAll(keyListMap.get(fieldAttrEntity.getAttr()));
                                    fieldAttrEntity.getSubForm().setItems(subExplainList);
                                } else {
                                    subExplainList.addAll(productIndex + 1,keyListMap.get(fieldAttrEntity.getAttr()));
                                    fieldAttrEntity.getSubForm().setItems(subExplainList);
                                }
                            }
                            if (keyListMap.size() == 1){
                                break;
                            }
                        }
                    }
                }
                saasHelp.handleListSpecialField(formDataListVO, XbbRefTypeEnum.CONTRACT.getCode());
                break;
            case PAYMENT_SHEET:
                analysisListProductData(dataList,dataIdList,businessType,corpid,1,null, formDataListDTO);
                break;
            case PAY_SHEET:
                analysisListProductData(dataList,dataIdList,businessType,corpid,1,null, formDataListDTO);
                break;
            case CUSTOMER_MANAGEMENT:
                saasHelp.handleListSpecialField(formDataListVO, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                analysisListProductData(dataList,dataIdList,businessType,corpid,1,null, formDataListDTO);
                break;
            case CREDIT_LIMIT:
                // 临时额度、已用额度、可用额度计算
                creditLimitService.calculateCreditLimit(corpid, formDataListDTO.getDistributorMark(), formDataListVO.getPaasFormDataESList());
                break;
            case CREDIT_TEMPORARY_LIMIT:
                // 过期状态判断
                for (PaasFormDataEntityExt entityExt : dataList) {
                    JSONObject data = entityExt.getData();
                    String temporaryStatus = data.getString(CreditTemporaryLimitEnum.APPLY_STATUS.getAttr());
                    int endTime = data.getIntValue(CreditTemporaryLimitEnum.END_TIME.getAttr());
                    if (endTime < DateTimeUtil.getTodayInt() && !Objects.equals(temporaryStatus, CreditTemporaryApplyStatusEnum.REVOKED.getCode())) {
                        data.put(CreditTemporaryLimitEnum.APPLY_STATUS.getAttr(), CreditTemporaryApplyStatusEnum.EXPIRED.getCode());
                    }
                }
                break;
            case CLUE:
                analysisListProductData(dataList,dataIdList,businessType,corpid,1,null, formDataListDTO);
                break;
            default:
                break;
        }
        //评分区间headList，特殊处理
//        hanlleHeadList4ScoreScreen(xbbRefTypeEnum,formDataListDTO,formDataListVO);
    }

    public void handleEsWorkOrderData4Show(FormDataListDTO formDataListDTO, WorkOrderDataEsListVO workOrderDataEsListVO) throws XbbException {
        List<WorkOrderEntityExt> workOrderEntityExts = workOrderDataEsListVO.getPaasFormDataESList();
        String corpid = formDataListDTO.getCorpid();
        List<Long> workOrderIdList = new ArrayList<>();
        if (workOrderEntityExts.isEmpty()){
            return;
        }
        Set<Long> templateIds = new HashSet<>();
        for (WorkOrderEntityExt workOrderEntityExt : workOrderEntityExts) {
            Long workOrderId = workOrderEntityExt.getId();
            workOrderIdList.add(workOrderId);
            templateIds.add(workOrderEntityExt.getTemplateId());
        }
        Map<Long, WorkOrderTemplateEntity> templateMap = workOrderTemplateModel.getTemplateMap(templateIds, corpid);

        Map<Long,String> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,String> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userTeamService.getUserMap(workOrderIdList,corpid,XbbRefTypeEnum.WORK_ORDER.getCode(),false,mainUserMap,coUserMap);
        Boolean nodeTime = Objects.equals(formDataListDTO.getDefaultGroup(),1) && (Objects.equals(formDataListDTO.getListGroupId(),(long)ListGroupEnum.WORK_ORDER_RESPONSE_BY_ME.getCode()));
        Map<Long,WorkOrderFlowNodeEntity> nodeMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<String> userIdList = new ArrayList<>();
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("del",0);
        param.put("workOrderIdIn",workOrderIdList);
        param.put("statusIn",Arrays.asList(WorkOrderNodeStatusEnum.UNACCEPTED.getCode(),WorkOrderNodeStatusEnum.ONGOING.getCode(), WorkOrderNodeStatusEnum.FINISH.getCode(), WorkOrderNodeStatusEnum.CLOSE.getCode(), WorkOrderNodeStatusEnum.ROLLBACK.getCode(),WorkOrderNodeStatusEnum.TRANSFERRED.getCode()));
        if (Objects.equals(formDataListDTO.getListGroupId(),(long)ListGroupEnum.WORK_ORDER_RESPONSE_BY_ME.getCode())){
            param.put("userId",formDataListDTO.getUserId());
        }else {
            UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
            Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, XbbRefTypeEnum.WORK_ORDER.getCode(), null);
            userIdList = userModel.getSubIdListByDataPermission(dataPermission, userEntity.getUserId(), userEntity.getCorpid(),BasicConstant.ONE,false);
            userIdList.add("-1");
            param.put("userIdIn",userIdList);
        }
        List<WorkOrderFlowNodeEntity> workOrderFlowNodeEntityList = workOrderFlowNodeModel.findEntitys(param);
        for (WorkOrderFlowNodeEntity entity : workOrderFlowNodeEntityList){
            nodeMap.put(entity.getWorkOrderId(),entity);
        }
        //用于存储阶段名称
        Map<Long,String> workOrderStageNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<WorkOrderStageEntity> workOrderStageEntityList = workOrderStageService.getStagesByTemplateIdIn(templateIds, corpid, false);
        for (WorkOrderStageEntity entity : workOrderStageEntityList) {
            workOrderStageNameMap.put(entity.getId(), entity.getName());
        }

        for (WorkOrderEntityExt entity : workOrderEntityExts){
            WorkOrderTemplateEntity workOrderTemplateEntity = templateMap.get(entity.getTemplateId());
            //不限时自由工单
            boolean isLimit = Objects.equals(workOrderTemplateEntity.getIsFree(), 1) && Objects.equals(workOrderTemplateEntity.getExpectedTime(), 0);

            JSONObject data = entity.getData();
            //老数据data中没有存阶段状态
            if (Objects.nonNull(data) && data.containsKey(WorkOrderEnum.NODE_STATUS.getAttr())){
                Integer nodeStatus = data.getInteger(WorkOrderEnum.NODE_STATUS.getAttr());
                if (Objects.isNull(nodeStatus)) {
                    data.put(FieldTypeEnum.WORK_ORDER_NODE_STATUS.getAlias(), "");
                } else {
                    data.put(FieldTypeEnum.WORK_ORDER_NODE_STATUS.getAlias(), WorkOrderNodeStatusEnum.getNameByCode(data.getInteger(WorkOrderEnum.NODE_STATUS.getAttr()),""));
                }
            } else {
                data.put(FieldTypeEnum.WORK_ORDER_NODE_STATUS.getAlias(), "");
            }
            data.put(FieldTypeEnum.SERIALNO.getAlias(),entity.getSerialNo());
            data.put(FieldTypeEnum.CLOSETIME.getAlias(),entity.getCloseTime());
            data.put(FieldTypeEnum.ENDTIME.getAlias(),entity.getEndTime());
            data.put(FieldTypeEnum.WORK_ORDER_STATUS.getAlias(),WorkOrderNodeStatusEnum.getByCode(entity.getStatus()).getName());
            data.put(FieldTypeEnum.WORK_ORDER_STAGE_NAME.getAlias(),workOrderStageNameMap.getOrDefault(entity.getNowStageId(), ""));
            if (isLimit) {
                //data.put(WorkOrderEnum.TIME_OUT.getAttr(), "");
                TimeConsumingOutPojo timeConsumingOutPojo =  workOrderBasicService.workOrderSpecialConsueTime(entity);
                data.put(WorkOrderEnum.TIME_OUT.getAttr(), timeConsumingOutPojo.getConsumeTimeStr());
            } else {
                if (nodeTime){
                    if (nodeMap.size() == 0) {
                        data.put(WorkOrderEnum.TIME_OUT.getAttr(), "");
                    } else {
                        data.put(WorkOrderEnum.TIME_OUT.getAttr(), workOrderBasicService.workOrderNodeConsueTime(nodeMap.get(entity.getId())).getConsumeTimeStr());
                    }
                } else {
                    TimeConsumingOutPojo timeConsumingOutPojo = workOrderBasicService.workOrderConsueTime(entity);
                    data.put(WorkOrderEnum.TIME_OUT.getAttr(), timeConsumingOutPojo.getConsumeTimeStr());
                    if (1 == timeConsumingOutPojo.getIsOut()) {
                        data.put("isRed",1);
                    }
                }
            }
        }
    }


    public Map<String, List<FieldAttrEntity>> analysisListProductData(List<PaasFormDataEntityExt> paasFormDataESList, List<Long> dataIdList, Integer businessType, String corpid, Integer page, Integer pageSize, FormDataListDTO formDataListDTO) throws XbbException{
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        Map<Long, List<JSONObject>> productDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<JSONObject>> materialDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Long> warehouseIds = new HashSet<>();
        Map<String,Map<Long, List<JSONObject>>> productAttr2Map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("startGroup",page);
        map.put("pageNumGroup",pageSize);
        if (Objects.isNull(pageSize)){
            map.put("orderByStrGroup", BasicConstant.SORT);
        } else {
            map.put("orderByStr", BasicConstant.SORT);
        }
        boolean productNameNeedHide = false;
        PaasFormExplainEntity productExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        if (Objects.nonNull(productExplain)) {
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMapByAttr(productExplain.getExplains(), ProductEnum.NAME.getAttr());
            FieldAttrEntity fieldAttrEntity = explainMap.get(ProductEnum.NAME.getAttr());
            if (Objects.equals(fieldAttrEntity.getVisibleScopeEnable(), 1)) {
                VisibleRulePoJo visibleScopeRule = fieldAttrEntity.getVisibleScopeRule();
                if (Objects.nonNull(visibleScopeRule)) {
                    fieldAttrEntity.getVisibleScopeRule().setRelative(new ArrayList<>());
                    HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
                    BeanUtil.copyProperties(formDataListDTO, handlerExplainDTO);
                    productNameNeedHide = ExplainUtil.isFieldNeedHide(fieldAttrEntity, handlerExplainDTO);
                }
            }
        }
        Map<String,FieldAttrEntity> expalinMap = formDataListDTO.getExplainMap();
        Map<String,List<FieldAttrEntity>> keyListMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Long> productIdSet = new HashSet<>();
        switch (xbbRefTypeEnum){
            case CONTRACT:
            case ORDER:
                if (!expalinMap.containsKey(ContractEnum.PRODUCT.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(ContractEnum.PRODUCT.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(ContractEnum.PRODUCT.getAttr())));
                }
                map.put("contractIdIn",dataIdList);
                map.put("type",XbbRefTypeEnum.CONTRACT.getCode());
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "contract_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                } else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                List<ContractProductEntity> contractProductEntityList = contractProductModel.findEntitys(map);
                for (ContractProductEntity entity : contractProductEntityList) {
                    Long contractId = entity.getContractId();
                    JSONObject productData = contractService.formatSingleProduct(entity);
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(), productNameNeedHide ? null : entity.getProductName());
                    List<JSONObject> productDataList = productDataMap.getOrDefault(contractId,new ArrayList<>());
                    productDataList.add(productData);
                    productDataMap.put(contractId,productDataList);
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(ContractEnum.PRODUCT.getAttr(),productDataMap);
                break;
            case PROMOTION_ACTIVITY_MANAGEMENT:
                if (!expalinMap.containsKey(PromotionActivityManagementEnum.APPLICABLE_PRODUCT.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(PromotionActivityManagementEnum.APPLICABLE_PRODUCT.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(PromotionActivityManagementEnum.APPLICABLE_PRODUCT.getAttr())));
                }
                map.put("refIdIn",dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "ref_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                } else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                List<PromotionProductEntity> entities = promotionProductModel.findEntities(map);
                for (PromotionProductEntity entity : entities) {
                    Long refId = entity.getRefId();
                    JSONObject productData = entity.getData();
                    productData.put(StringConstant.DATA_ID, entity.getProductId());
                    List<JSONObject> productDataList = productDataMap.getOrDefault(refId,new ArrayList<>());
                    productDataList.add(productData);
                    productDataMap.put(refId,productDataList);
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(PromotionActivityManagementEnum.APPLICABLE_PRODUCT.getAttr(),productDataMap);
                break;
            case SALES_OPPORTUNITY:
                if (!expalinMap.containsKey(SalesOpportunityEnum.PRODUCTS.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(SalesOpportunityEnum.PRODUCTS.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(SalesOpportunityEnum.PRODUCTS.getAttr())));
                }
                map.put("opportunityIdIn",dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "opportunity_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                List<OpportunityProductEntity> opportunityProductEntityList = opportunityProductModel.findEntitys(map);
                for (OpportunityProductEntity entity : opportunityProductEntityList) {
                    Long opportunityId = entity.getOpportunityId();
                    JSONObject productData = opportunityService.formatSingleProduct(entity);
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    List<JSONObject> productDataList = productDataMap.getOrDefault(opportunityId,new ArrayList<>());
                    productDataList.add(productData);
                    productDataMap.put(opportunityId,productDataList);
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(SalesOpportunityEnum.PRODUCTS.getAttr(),productDataMap);
                break;
            case PURCHASE:
                if (!expalinMap.containsKey(PurchaseEnum.PRODUCT.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(PurchaseEnum.PRODUCT.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(PurchaseEnum.PRODUCT.getAttr())));
                }
                map.put("purchaseIdIn",dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "purchase_sheet_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                List<PurchaseProductEntity> purchaseProductEntityList = purchaseProductModel.findEntitys(map);
                for (PurchaseProductEntity entity : purchaseProductEntityList) {
                    Long purchaseSheetId = entity.getPurchaseSheetId();
                    JSONObject productData = purchaseService.formatSingleProduct(entity);
                    // 多单位
//                    if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr()))) {
//                        List<UnitItemPoJo> unitItemPoJos = groupItemsMap.get(entity.getGroupId());
//                        productData.put(ProductConstant.TRANSFORM_UNIT_RATE, unitItemPoJos);
//                    }
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    List<JSONObject> productDataList = productDataMap.getOrDefault(purchaseSheetId,new ArrayList<>());
                    productDataList.add(productData);
                    productDataMap.put(purchaseSheetId,productDataList);
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(PurchaseEnum.PRODUCT.getAttr(),productDataMap);
                break;
            case RETURNED_PURCHASE:
                if (!expalinMap.containsKey(ReturnedPurchaseEnum.PRODUCTS.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(ReturnedPurchaseEnum.PRODUCTS.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(ReturnedPurchaseEnum.PRODUCTS.getAttr())));
                }
                map.put("returnPurchaseIdIn",dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "return_purchase_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                List<ReturnedPurchaseProductEntity> returnedPurchaseProductEntityList = returnedPurchaseProductModel.findEntitys(map);
                for (ReturnedPurchaseProductEntity entity : returnedPurchaseProductEntityList) {
                    Long returnPurchaseId = entity.getReturnPurchaseId();
                    JSONObject productData = returnedPurchaseService.formatSingleProduct(entity, false);
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    List<JSONObject> productDataList = productDataMap.getOrDefault(returnPurchaseId,new ArrayList<>());
                    productDataList.add(productData);
                    productDataMap.put(returnPurchaseId,productDataList);
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(ReturnedPurchaseEnum.PRODUCTS.getAttr(),productDataMap);
                break;
            case ASSEMBLE:
                if (!expalinMap.containsKey(AssembleEnum.IN_PRODUCTS.getAttr()) && !expalinMap.containsKey(AssembleEnum.OUT_PRODUCTS.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(AssembleEnum.IN_PRODUCTS.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(AssembleEnum.IN_PRODUCTS.getAttr())));
                    keyListMap.put(AssembleEnum.OUT_PRODUCTS.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(AssembleEnum.OUT_PRODUCTS.getAttr())));
                }
                map.put("assembleIdIn",dataIdList);
                map.put("type",1);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "assemble_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                List<AssembleProductEntity> assembleProductEntityList = assembleProductModel.findEntitys(map);
                List<Long> refIdInList = new ArrayList<>();
                assembleProductEntityList.forEach(item -> refIdInList.add(item.getId()));

                List<ProductBaseInfoEntity> productBaseInfoEntityList = productBaseInfoModel.getProductBaseInfoList(corpid,XbbRefTypeEnum.ASSEMBLE_PRODUCT.getCode(),refIdInList);
                Map<Long,ProductBaseInfoEntity> baseInfoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (ProductBaseInfoEntity entity : productBaseInfoEntityList){
                    baseInfoMap.put(entity.getRefId(),entity);
                }

                Map<Long, List<JSONObject>> outProductJsonMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (AssembleProductEntity entity : assembleProductEntityList) {
                    Long assembleId = entity.getAssembleId();
                    JSONObject productData = assembleService.formatSingleProduct(entity,baseInfoMap.getOrDefault(entity.getId(),new ProductBaseInfoEntity()));
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    List<JSONObject> productDataList = outProductJsonMap.getOrDefault(assembleId,new ArrayList<>());
                    productDataList.add(productData);
                    outProductJsonMap.put(assembleId,productDataList);
                    warehouseIds.add(entity.getWarehouseId());
                    productIdSet.add(entity.getProductId());
                }
                Map<Long, List<JSONObject>> inProductJsonMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                map.put("type",2);
                assembleProductEntityList = assembleProductModel.findEntitys(map);
                refIdInList.clear();
                assembleProductEntityList.forEach(item -> refIdInList.add(item.getId()));

                productBaseInfoEntityList = productBaseInfoModel.getProductBaseInfoList(corpid,XbbRefTypeEnum.ASSEMBLE_PRODUCT.getCode(),refIdInList);
                baseInfoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (ProductBaseInfoEntity entity : productBaseInfoEntityList){
                    baseInfoMap.put(entity.getRefId(),entity);
                }

                for (AssembleProductEntity entity : assembleProductEntityList) {
                    Long assembleId = entity.getAssembleId();
                    JSONObject productData = assembleService.formatSingleProduct(entity,baseInfoMap.getOrDefault(entity.getId(),new ProductBaseInfoEntity()));
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    List<JSONObject> productDataList = inProductJsonMap.getOrDefault(assembleId,new ArrayList<>());
                    productDataList.add(productData);
                    inProductJsonMap.put(assembleId,productDataList);
                    warehouseIds.add(entity.getWarehouseId());
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(AssembleEnum.OUT_PRODUCTS.getAttr(),outProductJsonMap);
                productAttr2Map.put(AssembleEnum.IN_PRODUCTS.getAttr(),inProductJsonMap);
                break;
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
                if (!expalinMap.containsKey(InstockEnum.PRODUCT.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(InstockEnum.PRODUCT.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(InstockEnum.PRODUCT.getAttr())));
                }
                map.put("instockIdIn",dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "into_warehouse_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                List<InstockProductEntity> instockProductEntityList = instockProductModel.findEntitys(map);
                for (InstockProductEntity entity : instockProductEntityList) {
                    Long warehouseId = entity.getWarehouseId();
                    Long intoWarehouseId = entity.getIntoWarehouseId();
                    JSONObject productData = instockService.formatSingleProduct(entity);
                    if (Objects.equals(businessType, XbbRefTypeEnum.REFUND_INSTOCK.getCode())) {
                        productData.put(SelectProductEnum.PRICE.getAttr(), entity.getPrice());
                        productData.put(SelectProductEnum.SUBTOTAL.getAttr(), entity.getPrice() * entity.getProductNum());
                    }
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    List<JSONObject> productDataList = productDataMap.getOrDefault(intoWarehouseId,new ArrayList<>());
                    productDataList.add(productData);
                    productDataMap.put(intoWarehouseId,productDataList);
                    warehouseIds.add(warehouseId);
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(InstockEnum.PRODUCT.getAttr(),productDataMap);
                break;
            case OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
                if (!expalinMap.containsKey(OutstockEnum.PRODUCT.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(OutstockEnum.PRODUCT.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(OutstockEnum.PRODUCT.getAttr())));
                }
                map.put("outstockIdIn",dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "out_warehouse_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                List<OutstockProductEntity> outstockProductEntityList = outstockProductModel.findEntitys(map);
                for (OutstockProductEntity entity : outstockProductEntityList) {
                    Long outWarehouseId = entity.getOutWarehouseId();
                    Long warehouseId = entity.getWarehouseId();
                    JSONObject productData = outstockService.formatSingleProduct(entity);
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    List<JSONObject> productDataList = productDataMap.getOrDefault(outWarehouseId,new ArrayList<>());
                    productDataList.add(productData);
                    productDataMap.put(outWarehouseId,productDataList);
                    warehouseIds.add(warehouseId);
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(OutstockEnum.PRODUCT.getAttr(),productDataMap);
                break;
            case PRODUCTION_MATERIEL_OUTSTOCK:
                if (!expalinMap.containsKey(OutstockEnum.PRODUCT.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(OutstockEnum.PRODUCT.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(OutstockEnum.PRODUCT.getAttr())));
                }
                map.put("outstockIdIn",dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "out_warehouse_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                outstockProductEntityList = outstockProductModel.findEntitys(map);
                for (OutstockProductEntity entity : outstockProductEntityList) {
                    Long outWarehouseId = entity.getOutWarehouseId();
                    Long warehouseId = entity.getWarehouseId();
                    JSONObject productData = outstockService.formatSingleProductionMaterielOutstockProduct(entity);
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    List<JSONObject> productDataList = productDataMap.getOrDefault(outWarehouseId,new ArrayList<>());
                    productDataList.add(productData);
                    productDataMap.put(outWarehouseId,productDataList);
                    warehouseIds.add(warehouseId);
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(OutstockEnum.PRODUCT.getAttr(),productDataMap);
                break;
            case CONTRACT_OUTSTOCK:
            case ORDER_OUTSTOCK:
                if (!expalinMap.containsKey(OutstockEnum.PRODUCT.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(OutstockEnum.PRODUCT.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(OutstockEnum.PRODUCT.getAttr())));
                }
                map.put("outstockIdIn",dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "out_warehouse_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                outstockProductEntityList = outstockProductModel.findEntitys(map);
                for (OutstockProductEntity entity : outstockProductEntityList) {
                    Long outWarehouseId = entity.getOutWarehouseId();
                    Long warehouseId = entity.getWarehouseId();
                    JSONObject productData = outstockService.formatSingleContractOutstockProduct(entity);
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    List<JSONObject> productDataList = productDataMap.getOrDefault(outWarehouseId,new ArrayList<>());
                    productDataList.add(productData);
                    productDataMap.put(outWarehouseId,productDataList);
                    warehouseIds.add(warehouseId);
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(OutstockEnum.PRODUCT.getAttr(),productDataMap);
                break;
            case CUSTOMER_STATEMENT:
            case CUSTOMER_STATEMENT_SNAPSHOT:
                if (!expalinMap.containsKey(CustomerStatementEnum.PRODUCT.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(CustomerStatementEnum.PRODUCT.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(CustomerStatementEnum.PRODUCT.getAttr())));
                }
                map.put("statementIdIn",dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "statement_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.ID);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.ID);
                }
                List<CustomerStatementProductEntity> customerStatementProductEntityList = customerStatementProductModel.findEntitys(map);
                for (CustomerStatementProductEntity productEntity : customerStatementProductEntityList) {
                    JSONObject productData = new JSONObject();
                    productData.put(StringConstant.DATA_ID, productEntity.getProductId());
                    productData.put(CustomerStatementProductEnum.PRODUCT.getAttr(), productEntity.getProductName());
                    productData.put(CustomerStatementProductEnum.SELLING_PRICE.getAttr(), productEntity.getProductPrice());
                    productData.put(CustomerStatementProductEnum.NUM.getAttr(), productEntity.getProductNum());
                    productData.put(CustomerStatementProductEnum.SUBTOTAL.getAttr(), Arith.mul(productEntity.getProductPrice(), productEntity.getProductNum()));
                    List<JSONObject> productDataList = productDataMap.getOrDefault(productEntity.getStatementId(), new LinkedList<>());
                    productDataList.add(productData);
                    productDataMap.put(productEntity.getStatementId(), productDataList);
                    productIdSet.add(productEntity.getProductId());
                }
                productAttr2Map.put(CustomerStatementEnum.PRODUCT.getAttr(), productDataMap);
                break;
            case INVENTORY:
                if (!expalinMap.containsKey(InventoryEnum.PRODUCT.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(InventoryEnum.PRODUCT.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(InventoryEnum.PRODUCT.getAttr())));
                }
                map.put("inventoryIdIn",dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "inventory_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                List<InventoryProductEntity> inventoryProductEntityList = inventoryProductModel.findEntitys(map);
                List<Long> refIdIn = new ArrayList<>();
                inventoryProductEntityList.forEach(item -> refIdIn.add(item.getId()));
                productBaseInfoEntityList =  productBaseInfoModel.getProductBaseInfoList(corpid,XbbRefTypeEnum.INVENTORY_PRODUCT.getCode(),refIdIn);
                baseInfoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (ProductBaseInfoEntity entity : productBaseInfoEntityList){
                    baseInfoMap.put(entity.getRefId(),entity);
                }

                for (InventoryProductEntity entity : inventoryProductEntityList) {
                    Long inventoryId = entity.getInventoryId();
                    JSONObject productData = inventoryService.formatSingleProduct(entity,baseInfoMap.getOrDefault(entity.getId(),new ProductBaseInfoEntity()));
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    List<JSONObject> productDataList = productDataMap.getOrDefault(inventoryId,new ArrayList<>());
                    productDataList.add(productData);
                    productDataMap.put(inventoryId,productDataList);
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(InventoryEnum.PRODUCT.getAttr(),productDataMap);
                break;
            case TRANSFER:
                if (!expalinMap.containsKey(TransferEnum.PRODUCTS.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(TransferEnum.PRODUCTS.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(TransferEnum.PRODUCTS.getAttr())));
                }
                Map<String, FieldAttrEntity> explainMap = formDataListDTO.getExplainMap();
                if (Objects.nonNull(explainMap.get(TransferEnum.TRANSFER_TYPE.getAttr()))) {
                    FieldAttrEntity fieldAttrEntity = explainMap.get(TransferEnum.TRANSFER_TYPE.getAttr());
                    fieldAttrEntity.setFieldType(FieldTypeEnum.COMBO.getType());
                }
                map.put("transferIdIn",dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "transfer_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                List<TransferProductEntity> transferProductEntityList = transferProductModel.findEntitys(map);
                List<Long> refIdList = new ArrayList<>();
                transferProductEntityList.forEach(item -> refIdList.add(item.getId()));
                productBaseInfoEntityList =  productBaseInfoModel.getProductBaseInfoList(corpid,XbbRefTypeEnum.TRANSFER_PRODUCT.getCode(),refIdList);
                baseInfoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (ProductBaseInfoEntity entity : productBaseInfoEntityList){
                    baseInfoMap.put(entity.getRefId(),entity);
                }
                for (TransferProductEntity entity : transferProductEntityList) {
                    Long transferId = entity.getTransferId();
                    JSONObject productData = transferService.formatSingleProduct(entity,baseInfoMap.getOrDefault(entity.getId(),new ProductBaseInfoEntity()));
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    List<JSONObject> productDataList = productDataMap.getOrDefault(transferId,new ArrayList<>());
                    productDataList.add(productData);
                    productDataMap.put(transferId,productDataList);
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(TransferEnum.PRODUCTS.getAttr(),productDataMap);
                break;
            case REFUND:
            case RETURN:
                if (!expalinMap.containsKey(RefundEnum.PRODUCTS.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(RefundEnum.PRODUCTS.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(RefundEnum.PRODUCTS.getAttr())));
                }
                Map<Long, Long> refundAndContract = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                List<Long> refundContractIdList = new ArrayList<>();
                refundContractIdList.add(-1L);
                Map<Long,Long> refundProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (PaasFormDataEntityExt entity : paasFormDataESList) {
                    JSONObject refundObject = entity.getData();
                    if (refundObject == null) {
                        break;
                    }
                    Long refConId = refundObject.getLong(RefundEnum.RED_CONTRACT_ID.getAttr());
                    refundContractIdList.add(refConId);
                    refundAndContract.put(refConId,entity.getId());
                    refundProductMap.put(refConId,entity.getDataId());
                }
                map.put("contractIdIn", refundContractIdList);
                map.put("type",XbbRefTypeEnum.REFUND.getCode());
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "contract_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                List<ContractProductEntity> redContractProductEntityList = contractProductModel.findEntitys(map);
                for (ContractProductEntity entity : redContractProductEntityList) {
                    Long contractId = entity.getContractId();
                    if (refundProductMap.containsKey(contractId)) {
                        JSONObject productData = contractService.formatSingleRefundProduct(entity);
                        if (Objects.isNull(productData.get(ProductEnum.PRICE.getAttr()))) {
                            productData.put(ProductEnum.PRICE.getAttr(),entity.getPrice());
                        }
                        productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                        productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                        List<JSONObject> productDataList = productDataMap.getOrDefault(refundProductMap.get(contractId), new ArrayList<>());
                        productDataList.add(productData);
                        productDataMap.put(refundProductMap.get(contractId),productDataList);
                        productIdSet.add(entity.getProductId());
                    }
                }
                productAttr2Map.put(RefundEnum.PRODUCTS.getAttr(),productDataMap);
                break;
            case WORK_ORDER:
                if (!expalinMap.containsKey(WorkOrderEnum.SPARE_PARTS.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(WorkOrderEnum.SPARE_PARTS.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(WorkOrderEnum.SPARE_PARTS.getAttr())));
                }
                map.put("workOrderIdIn", dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "work_order_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                List<WorkOrderProductEntity> workOrderProductEntityList = workOrderProductModel.findEntitys(map);
                for (WorkOrderProductEntity entity : workOrderProductEntityList) {
                    Long workOrderId = entity.getWorkOrderId();
                    JSONObject productData = workOrderService.formatSingleProduct(entity);
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    List<JSONObject> productDataList = productDataMap.getOrDefault(workOrderId,new ArrayList<>());
                    productDataList.add(productData);
                    productDataMap.put(workOrderId,productDataList);
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(WorkOrderEnum.SPARE_PARTS.getAttr(),productDataMap);
                break;
            case QUOTATION:
                if (!expalinMap.containsKey(QuotationEnum.PRODUCT.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(QuotationEnum.PRODUCT.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(QuotationEnum.PRODUCT.getAttr())));
                }
                map.put("quotationIdIn",dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "quotation_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                List<QuotationProductEntity> quotationProducts = quotationProductModel.findEntitys(map);
                for (QuotationProductEntity entity : quotationProducts) {
                    Long quotationId = entity.getQuotationId();
                    JSONObject productData = quotationService.formatSingleProduct(entity);
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    List<JSONObject> productDataList = productDataMap.getOrDefault(quotationId,new ArrayList<>());
                    productDataList.add(productData);
                    productDataMap.put(quotationId,productDataList);
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(QuotationEnum.PRODUCT.getAttr(),productDataMap);
                break;
            case BOM_BILL:
                if (!expalinMap.containsKey(BomBillEnum.PRODUCT.getAttr()) && !expalinMap.containsKey(BomBillEnum.MATERIEL.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(BomBillEnum.PRODUCT.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(BomBillEnum.PRODUCT.getAttr())));
                    keyListMap.put(BomBillEnum.MATERIEL.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(BomBillEnum.MATERIEL.getAttr())));
                }
                map.put("bomIdIn",dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "bom_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                map.put("type",1);
                List<BomProductEntity> bomProductEntityList = bomProductModel.findEntitys(map);
                for (BomProductEntity entity : bomProductEntityList) {
                    Long bomId = entity.getBomId();
                    Integer type = entity.getType();
                    JSONObject productData;
                    List<JSONObject> productDataList = productDataMap.getOrDefault(bomId,new ArrayList<>());
                    productData = bomBillService.formatSingleProduct(entity);
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    productData.put(SelectProductEnum.PRODUCT_NO.getAttr(),entity.getProductNo());
                    productData.put(SelectProductEnum.SPECIFICATION.getAttr(),specificationModel.joinSpecification(entity.getProductSpecification()));
                    productDataList.add(productData);
                    productDataMap.put(bomId,productDataList);
                    productIdSet.add(entity.getProductId());
                }
                map.put("type",2);
                bomProductEntityList = bomProductModel.findEntitys(map);
                for (BomProductEntity entity : bomProductEntityList) {
                    Long bomId = entity.getBomId();
                    Integer type = entity.getType();
                    JSONObject productData;
                    List<JSONObject> materialDataList = materialDataMap.getOrDefault(bomId,new ArrayList<>());
                    productData = bomBillService.formatSingleMaterial(entity);
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    materialDataList.add(productData);
                    materialDataMap.put(bomId,materialDataList);
                    productIdSet.add(entity.getProductId());

                }
                for (PaasFormDataEntityExt entityExt : paasFormDataESList) {
                    if (!productDataMap.containsKey(entityExt.getDataId())) {
                        continue;
                    }
                    List<JSONObject> jsonObjects = productDataMap.get(entityExt.getDataId());
                    if (CollectionsUtil.isEmpty(jsonObjects)) {
                        continue;
                    }
                    JSONObject jsonObject = jsonObjects.get(0);
                    JSONObject data = entityExt.getData();
                    data.put(BomBillEnum.PRODUCT_NAME_HIDE.getAttr(), jsonObject.get(ProductEnum.NAME.getAttr()));
                    data.put(BomBillEnum.PRODUCT_NAME.getAttr(), jsonObject.get(ProductEnum.NAME.getAttr()));
                    data.put(BomBillEnum.PRODUCT_NO.getAttr(), jsonObject.get(ProductEnum.PRODUCT_NO.getSaasAttr()));
                    data.put(BomBillEnum.PRODUCT_SPECIFICATION.getAttr(), jsonObject.get(SelectProductEnum.SPECIFICATION.getAttr()));
                    data.put(BomBillEnum.PRODUCT_UNIT.getAttr(), jsonObject.get(ProductEnum.UNIT.getAttr()));
                }
                productAttr2Map.put(BomBillEnum.PRODUCT.getAttr(),productDataMap);
                productAttr2Map.put(BomBillEnum.MATERIEL.getAttr(),materialDataMap);
                break;
            case PAYMENT_SHEET:
                for (PaasFormDataEntityExt entityExt : paasFormDataESList) {
                    JSONObject data = entityExt.getData();
                    String invoiceAmountAttr = PaymentSheetEnum.INVOICE_AMOUNT.getAttr();
                    Double invoiceAmount = data.getDouble(invoiceAmountAttr);
                    if (invoiceAmount == null) {
                        data.put(invoiceAmountAttr, 0D);
                    }
                }
                break;
            case PAY_SHEET:
                for (PaasFormDataEntityExt entityExt : paasFormDataESList) {
                    JSONObject data = entityExt.getData();
                    String invoiceAmountAttr = PaySheetEnum.INVOICE_AMOUNT.getAttr();
                    Double invoiceAmount = data.getDouble(invoiceAmountAttr);
                    if (invoiceAmount == null) {
                        data.put(invoiceAmountAttr, 0D);
                    }
                }
                break;
            case PRODUCTION_ORDER:
                if (!expalinMap.containsKey(ProductionOrderEnum.PRODUCT.getAttr()) && !expalinMap.containsKey(ProductionOrderEnum.MATERIEL.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(ProductionOrderEnum.PRODUCT.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(ProductionOrderEnum.PRODUCT.getAttr())));
                    keyListMap.put(ProductionOrderEnum.MATERIEL.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(ProductionOrderEnum.MATERIEL.getAttr())));
                }
                map.put("proOrderIdIn",dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "production_order_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                map.put("type",1);
                List<ProductionOrderProductEntity> productionOrderProductEntityList = productionOrderProductModel.findEntitys(map);
                for (ProductionOrderProductEntity entity : productionOrderProductEntityList) {
                    Long productionOrderId = entity.getProductionOrderId();
                    Integer type = entity.getType();
                    JSONObject productData;
                    List<JSONObject> productDataList = productDataMap.getOrDefault(productionOrderId,new ArrayList<>());
                    productData = productionOrderService.formatSingleProduct(entity);
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    productDataList.add(productData);
                    productDataMap.put(productionOrderId,productDataList);
                    productIdSet.add(entity.getProductId());
                }
                map.put("type",2);
                productionOrderProductEntityList = productionOrderProductModel.findEntitys(map);
                for (ProductionOrderProductEntity entity : productionOrderProductEntityList) {
                    Long productionOrderId = entity.getProductionOrderId();
                    JSONObject productData;
                    List<JSONObject> materialDataList = materialDataMap.getOrDefault(productionOrderId,new ArrayList<>());
                    productData = productionOrderService.formatSingleMaterial(entity);
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    materialDataList.add(productData);
                    materialDataMap.put(productionOrderId,materialDataList);
                    // 23914 Web生产单(老数据)列表页，物料的仓库信息未展示。
                    JSONArray wareHouseArray = productData.getJSONArray(ProductionOrderMaterielProductEnum.WAREHOUSE.getAttr());
                    for (Object object : wareHouseArray) {
                        JSONObject wareHouseData = (JSONObject) object;
                        String wareHouseName = wareHouseData.getString(StringConstant.SAAS_LINK_BUSINESS_NAME);
                        if (Objects.isNull(wareHouseName) || wareHouseName.isEmpty()) {
                            WarehouseEntityExt warehouseEntityExt = warehouseModel.getByKey(wareHouseData.getLong(StringConstant.SAAS_LINK_BUSINESS_ID), corpid);
                            if (Objects.nonNull(warehouseEntityExt)) {
                                wareHouseData.put(StringConstant.SAAS_LINK_BUSINESS_NAME, warehouseEntityExt.getData().getString(WarehouseEnum.WAREHOUSE_NAME.getAttr()));
                            }
                        }
                    }
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(ProductionOrderEnum.PRODUCT.getAttr(),productDataMap);
                productAttr2Map.put(ProductionOrderEnum.MATERIEL.getAttr(),materialDataMap);
                break;
            case COST_ADJUST:
                if (!expalinMap.containsKey(CostAdjustEnum.PRODUCT.getAttr())){
                    return keyListMap;
                }else {
                    keyListMap.put(CostAdjustEnum.PRODUCT.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(formDataListDTO.getExplainMap().get(CostAdjustEnum.PRODUCT.getAttr())));
                }
                map.put("costAdjustIdIn",dataIdList);
                if (Objects.isNull(pageSize)) {
                    map.put("groupByStr", "cost_adjust_id");
                    map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
                }else {
                    map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
                }
                List<CostAdjustProductEntity> productEntityList = costAdjustProductModel.findEntitys(map);
                List<Long> warehouseIdList = productEntityList.stream().map(CostAdjustProductEntity::getWarehouseId).collect(Collectors.toList());
                List<PaasFormDataEntityExt> warehouseList = paasEsModel.getByIdList(warehouseIdList, corpid, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.WAREHOUSE.getCode(), new ArrayList<>(), IndexTypeEnum.IDX_SAAS_WAREHOUSE);
                for (CostAdjustProductEntity entity : productEntityList) {
                    Long costAdjustId = entity.getCostAdjustId();
                    Long warehouseId = entity.getWarehouseId();
                    JSONObject productData = costAdjustProductModel.formatSingleProduct(entity, warehouseList);
                    // 将仓库信息改为仓库ID
                    productData.put(CostAdjustProductEnum.WAREHOUSE.getAttr(), warehouseId);
                    productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                    productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : entity.getProductName());
                    List<JSONObject> productDataList = productDataMap.getOrDefault(costAdjustId, new ArrayList<>());
                    productDataList.add(productData);
                    productDataMap.put(costAdjustId, productDataList);
                    warehouseIds.add(warehouseId);
                    productIdSet.add(entity.getProductId());
                }
                productAttr2Map.put(CostAdjustEnum.PRODUCT.getAttr(),productDataMap);
                break;
            default:
                break;
        }
        if (keyListMap.isEmpty()){
            return keyListMap;
        }
        Map<Long,PaasFormDataEntityExt> productMap = new HashMap<>();
        //获取关联字段
        //获取产品数据，最多200条
        if (!productIdSet.isEmpty()){
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword",corpid))
                    .filter(termsQuery(FieldTypeEnum.DATAID.getAlias(),productIdSet));
            SearchRequest searchRequest = EsUtil.simplePackageForQueryForPage(IndexTypeEnum.IDX_SAAS_PRODUCT,boolQueryBuilder,null,0, productIdSet.size());
            XbbAggregatedPage<PaasFormDataEntityExt> result = xbbElasticsearchRestTemplate.queryForPages(searchRequest,PaasFormDataEntityExt.class);
            List<PaasFormDataEntityExt> productList = result.getContent();
//            List<PaasFormDataEntityExt> productList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT,boolQueryBuilder, PaasFormDataEntityExt.class,null);
            productService.setChildSpecification(productList,corpid);
            for (PaasFormDataEntityExt entityExt : productList) {
                productMap.put(entityExt.getDataId(),entityExt);
            }
        }
        if (!warehouseIds.isEmpty()) {
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder
                    .filter(termQuery("corpid.keyword", corpid))
                    .filter(termQuery("del", 0))
                    .filter(termsQuery(FieldTypeEnum.DATAID.getAlias(),warehouseIds));
            try {
                SearchRequest searchRequest = EsUtil.simplePackageForQueryForPage(IndexTypeEnum.IDX_SAAS_WAREHOUSE,boolQueryBuilder,Arrays.asList(FieldTypeEnum.DATAID.getAlias(), WarehouseEnum.WAREHOUSE_NAME.getAttr()), 0, warehouseIds.size());
                XbbAggregatedPage<PaasFormDataEntityExt> result = xbbElasticsearchRestTemplate.queryForPages(searchRequest,PaasFormDataEntityExt.class);
                List<PaasFormDataEntityExt> warehouseEntitys = result.getContent();
//                List<PaasFormDataEntity> warehouseEntitys = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_WAREHOUSE, boolQueryBuilder, PaasFormDataEntity.class, Arrays.asList(FieldTypeEnum.DATAID.getAlias(), WarehouseEnum.getAttrConnectData(WarehouseEnum.WAREHOUSE_NAME)));
                Map<Long,String> warehouseNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                warehouseEntitys.forEach(item -> warehouseNameMap.put(item.getDataId(),item.getData().getString(WarehouseEnum.WAREHOUSE_NAME.getAttr())));
                for (Map.Entry<String, Map<Long, List<JSONObject>>> stringMapEntry : productAttr2Map.entrySet()) {
                    Map<Long, List<JSONObject>> value = stringMapEntry.getValue();
                    for (Map.Entry<Long, List<JSONObject>> longListEntry : value.entrySet()) {
                        List<JSONObject> value1 = longListEntry.getValue();
                        for (JSONObject object : value1) {
                            Long warehouseId = object.getLong(SelectProductEnum.WAREHOUSE.getAttr());
                            if (warehouseNameMap.containsKey(warehouseId)) {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, warehouseId);
                                jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME, warehouseNameMap.get(warehouseId));
                                jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_LINK_TYPE,XbbRefTypeEnum.WAREHOUSE.getCode());
                                jsonObject.put(StringConstant.SAAS_MARK, SaasMarkEnum.SAAS.getCode());
                                object.put(ProductionOrderMaterielProductEnum.WAREHOUSE.getAttr(),Collections.singleton(jsonObject));
                            }
                        }
                    }
                }
            } catch (XbbException e) {
                Log.error("SaasListHelp.analysisListProductData查询仓库名字报错",e);
                e.printStackTrace();
            }
        }
        Map<Long, List<UnitItemPoJo>> groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
        Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
        Map<String, String> productUnitItemMap = relativeProductHelp.getProductUnitItemMap(corpid);
        for (PaasFormDataEntityExt entity : paasFormDataESList) {
            //最多两次循环
            for (Map.Entry<String,Map<Long, List<JSONObject>>> entry : productAttr2Map.entrySet()){
                if (entry.getValue().containsKey(entity.getDataId())){
                    if (keyListMap.containsKey(entry.getKey()) && !keyListMap.get(entry.getKey()).isEmpty()){
                        //有关联字段，最多一次循环
                        for (JSONObject jsonObject : entry.getValue().get(entity.getDataId())) {
                            if (productMap.containsKey(jsonObject.getLong(StringConstant.DATA_ID))){
                                PaasFormDataEntityExt product = productMap.get(jsonObject.getLong(StringConstant.DATA_ID));
                                for (FieldAttrEntity item : keyListMap.get(entry.getKey())){
                                    if (Objects.equals(item.getFieldType(),FieldTypeEnum.SERIALNO.getType())){
                                        jsonObject.put(item.getAttr(), product.getSerialNo());
                                    }else if (Objects.equals(item.getFieldType(),FieldTypeEnum.ADDTIME.getType())){
                                        jsonObject.put(item.getAttr(), product.getAddTime());
                                    }else if (Objects.equals(item.getFieldType(),FieldTypeEnum.UPDATETIME.getType())){
                                        jsonObject.put(item.getAttr(), product.getUpdateTime());
                                    }else {
                                        jsonObject.put(item.getAttr(), product.getData().get(item.getSaasAttr()));
                                    }
                                }
                                // 多单位
                                JSONObject productData = product.getData();
                                if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                                    String businessUnitVal = jsonObject.getString(SelectProductEnum.UNIT.getAttr());
                                    long unitGroupId = productData.getLongValue(ProductEnum.UNIT.getAttr());
                                    List<UnitItemPoJo> unitItemPoJos = groupItemsMap.get(unitGroupId);
                                    jsonObject.put(ProductConstant.TRANSFORM_UNIT_RATE, unitItemPoJos);
                                    if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCTION_ORDER.getCode()) && Objects.equals(entry.getKey(), ProductionOrderEnum.PRODUCT.getAttr())) {
                                        entity.getData().put(ProductConstant.TRANSFORM_UNIT_RATE, unitItemPoJos);
                                    }
                                    if (!StringUtil.isDigital(businessUnitVal) || Long.parseLong(businessUnitVal) < ProductConstant.MAX_SINGLE_UNIT_VALUE) {
                                        MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.getOrDefault(unitGroupId, new MultiUnitItemPoJo());
                                        jsonObject.put(SelectProductEnum.UNIT.getAttr(), multiUnitItemPoJo.getBaseValue());
                                    }
                                }

                                if (Objects.equals(businessType, XbbRefTypeEnum.COST_ADJUST.getCode())) {
                                    String unitGroupId = productData.getString(ProductEnum.UNIT.getAttr());
                                    if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                                        MultiUnitItemPoJo unitItemPoJo = groupBaseUnitMap.getOrDefault(Long.valueOf(unitGroupId), new MultiUnitItemPoJo());
                                        jsonObject.put(XbbRefTypeEnum.PRODUCT.getCode()+","+SelectProductEnum.UNIT.getAttr(), unitItemPoJo.getText());
                                        jsonObject.put(CostAdjustProductEnum.BASIC_UNIT.getAttr(), unitItemPoJo.getBaseName());
                                    } else {
                                        String unit = productUnitItemMap.getOrDefault(unitGroupId, unitGroupId);
                                        jsonObject.put(XbbRefTypeEnum.PRODUCT.getCode() + "," + SelectProductEnum.UNIT.getAttr(), unit);
                                        jsonObject.put(CostAdjustProductEnum.BASIC_UNIT.getAttr(), unit);

                                    }
                                }



                            }
                        }
                    }
                    entity.getData().put(entry.getKey(), entry.getValue().get(entity.getDataId()));
                }else {
                    entity.getData().put(entry.getKey(), new ArrayList<>());
                }
            }
        }
        return keyListMap;
    }

    public Map<String, List<FieldAttrEntity>> analysisListWorkOrderProductData(List<WorkOrderEntityExt> paasFormDataESList, List<Long> dataIdList, Integer businessType, String corpid, Integer page, Integer pageSize, Map<String, FieldAttrEntity> expalinMap) throws XbbException {
        Map<String,List<FieldAttrEntity>> keyListMap = new HashMap<>();
        Set<Long> productIdSet = new HashSet<>();
        if (!expalinMap.containsKey(WorkOrderEnum.SPARE_PARTS.getAttr())){
            return keyListMap;
        }else {
            keyListMap.put(WorkOrderEnum.SPARE_PARTS.getAttr(), formDataValidateProductHelp.listProductLinkKeyField(expalinMap.get(WorkOrderEnum.SPARE_PARTS.getAttr())));
        }
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("start",page);
        map.put("pageNum",pageSize);
        map.put("workOrderIdIn", dataIdList);
        map.put("orderByStr","id");
        List<WorkOrderProductEntity> workOrderProductEntityList = workOrderProductModel.findEntitys(map);
        Map<String,Map<Long, List<JSONObject>>> productAttr2Map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<JSONObject>> productDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (WorkOrderProductEntity entity : workOrderProductEntityList) {
            productIdSet.add(entity.getProductId());
            Long workOrderId = entity.getWorkOrderId();
            JSONObject productData = workOrderService.formatSingleProduct(entity);
            productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
            productData.put(SelectProductEnum.PRODUCT.getAttr(),entity.getProductName());
            List<JSONObject> productDataList = productDataMap.getOrDefault(workOrderId,new ArrayList<>());
            productDataList.add(productData);
            productDataMap.put(workOrderId,productDataList);
        }
        productAttr2Map.put(WorkOrderEnum.SPARE_PARTS.getAttr(),productDataMap);
        if (keyListMap.isEmpty()){
            return keyListMap;
        }
        Map<Long,PaasFormDataEntityExt> productMap = new HashMap<>();
        //获取关联字段
        //获取产品数据，最多200条
        if (!productIdSet.isEmpty()){
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword",corpid))
                    .filter(termsQuery(FieldTypeEnum.DATAID.getAlias(),productIdSet));
            List<PaasFormDataEntityExt> productList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT,boolQueryBuilder, PaasFormDataEntityExt.class,null);
            productService.setChildSpecification(productList,corpid);
            for (PaasFormDataEntityExt entityExt : productList) {
                productMap.put(entityExt.getDataId(),entityExt);
            }
        }
        Map<Long, List<UnitItemPoJo>> groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
        Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
        for (PaasFormDataEntityExt entity : paasFormDataESList) {
            for (Map.Entry<String,Map<Long, List<JSONObject>>> entry : productAttr2Map.entrySet()){
                if (entry.getValue().containsKey(entity.getDataId())){
                    if (keyListMap.containsKey(entry.getKey()) && !keyListMap.get(entry.getKey()).isEmpty()){
                        //有关联字段，最多一次循环
                        for (JSONObject jsonObject : entry.getValue().get(entity.getDataId())) {
                            if (productMap.containsKey(jsonObject.getLong(StringConstant.DATA_ID))){
                                PaasFormDataEntityExt product = productMap.get(jsonObject.getLong(StringConstant.DATA_ID));
                                for (FieldAttrEntity item : keyListMap.get(entry.getKey())){
                                    if (Objects.equals(item.getFieldType(),FieldTypeEnum.SERIALNO.getType())){
                                        jsonObject.put(item.getAttr(), product.getSerialNo());
                                    }else if (Objects.equals(item.getFieldType(),FieldTypeEnum.ADDTIME.getType())){
                                        jsonObject.put(item.getAttr(), product.getAddTime());
                                    }else if (Objects.equals(item.getFieldType(),FieldTypeEnum.UPDATETIME.getType())){
                                        jsonObject.put(item.getAttr(), product.getUpdateTime());
                                    }else {
                                        jsonObject.put(item.getAttr(), product.getData().get(item.getSaasAttr()));
                                    }
                                }
                                Integer enableMultiUnit = product.getData().getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr());
                                if (BasicConstant.ONE.equals(enableMultiUnit)) {
                                    String businessUnitVal = jsonObject.getString(SelectProductEnum.UNIT.getAttr());
                                    long unitGroupId = product.getData().getLongValue(ProductEnum.UNIT.getAttr());
                                    List<UnitItemPoJo> unitItemPoJos = groupItemsMap.get(unitGroupId);
                                    jsonObject.put(ProductConstant.TRANSFORM_UNIT_RATE, unitItemPoJos);
                                    if (!StringUtil.isDigital(businessUnitVal) || Long.parseLong(businessUnitVal) < ProductConstant.MAX_SINGLE_UNIT_VALUE) {
                                        MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(unitGroupId);
                                        jsonObject.put(SelectProductEnum.UNIT.getAttr(), multiUnitItemPoJo.getBaseValue());
                                    }
                                }
                            }
                        }
                    }
                    entity.getData().put(entry.getKey(), entry.getValue().get(entity.getDataId()));
                }else {
                    entity.getData().put(entry.getKey(), new ArrayList<>());
                }
            }
        }
        return keyListMap;
    }

    public void handleEsData4Show(FormDataListDTO formDataListDTO, WorkOrderDataEsListVO workOrderDataEsListVO) throws XbbException {
        List<WorkOrderEntityExt> workOrderEntityExts = workOrderDataEsListVO.getPaasFormDataESList();
        String corpid = formDataListDTO.getCorpid();
        List<Long> workOrderIdList = new ArrayList<>();
        if (workOrderEntityExts.isEmpty()){
            return;
        }
        Set<Long> templateIds = new HashSet<>();
        for (WorkOrderEntityExt workOrderEntityExt : workOrderEntityExts) {
            Long workOrderId = workOrderEntityExt.getId();
            workOrderIdList.add(workOrderId);
            templateIds.add(workOrderEntityExt.getTemplateId());
        }
        Map<Long, WorkOrderTemplateEntity> templateMap = workOrderTemplateModel.getTemplateMap(templateIds, corpid);

        if (Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(formDataListDTO.getFromExport(), 0)){
            //工单导出走了列表页，但后面要解析完整数据仍要重新查询，所以这里导出跳过
            Map<String,List<FieldAttrEntity>> keyListMap = analysisListWorkOrderProductData(workOrderEntityExts,workOrderIdList,XbbRefTypeEnum.WORK_ORDER.getCode(),corpid,1,null,formDataListDTO.getExplainMap());
            if (!keyListMap.isEmpty()){
                for (FieldAttrEntity fieldAttrEntity : workOrderDataEsListVO.getHeadList()) {
                    if (keyListMap.containsKey(fieldAttrEntity.getAttr())){
                        int index = 0;
                        int productIndex = -1;
                        SubFormPoJo subForm = fieldAttrEntity.getSubForm();
                        if (subForm != null && subForm.getItems() != null) {
                            List<FieldAttrEntity> subExplainList = (List<FieldAttrEntity>) subForm.getItems();
                            for (FieldAttrEntity field : subExplainList) {
                                index++;
                                if (Objects.equals(field.getAttr(),SelectProductEnum.PRODUCT.getAttr())){
                                    productIndex = index;
                                    break;
                                }
                            }
                            if (index >= 0){
                                if (subForm != null && subForm.getItems() != null) {
                                    subExplainList.addAll(productIndex,keyListMap.getOrDefault(fieldAttrEntity.getAttr(), new ArrayList<>()));
                                    subForm.setItems(subExplainList);
                                }
                            }
                        }
                        break;

                    }
                }
            }
        }
        Map<Long,String> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,String> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userTeamService.getUserMap(workOrderIdList,corpid,XbbRefTypeEnum.WORK_ORDER.getCode(),false,mainUserMap,coUserMap);
        Boolean nodeTime = Objects.equals(formDataListDTO.getDefaultGroup(),1) && (Objects.equals(formDataListDTO.getListGroupId(),(long)ListGroupEnum.WORK_ORDER_RESPONSE_BY_ME.getCode()));
        Map<Long,WorkOrderFlowNodeEntity> nodeMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<String> userIdList = new ArrayList<>();
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("del",0);
        param.put("workOrderIdIn",workOrderIdList);
        param.put("statusIn",Arrays.asList(WorkOrderNodeStatusEnum.UNACCEPTED.getCode(),WorkOrderNodeStatusEnum.ONGOING.getCode(), WorkOrderNodeStatusEnum.FINISH.getCode(), WorkOrderNodeStatusEnum.CLOSE.getCode(), WorkOrderNodeStatusEnum.ROLLBACK.getCode(),WorkOrderNodeStatusEnum.TRANSFERRED.getCode()));
        if (Objects.equals(formDataListDTO.getListGroupId(),(long)ListGroupEnum.WORK_ORDER_RESPONSE_BY_ME.getCode())){
            param.put("userId",formDataListDTO.getUserId());
        }else {
            UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
            Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, XbbRefTypeEnum.WORK_ORDER.getCode(), null);
            userIdList = userModel.getSubIdListByDataPermission(dataPermission, userEntity.getUserId(), userEntity.getCorpid(), BasicConstant.ONE,false);
            userIdList.add("-1");
            param.put("userIdIn",userIdList);
        }
        List<WorkOrderFlowNodeEntity> workOrderFlowNodeEntityList = workOrderFlowNodeModel.findEntitys(param);
        for (WorkOrderFlowNodeEntity entity : workOrderFlowNodeEntityList){
            nodeMap.put(entity.getWorkOrderId(),entity);
        }
        //用于存储阶段名称
        Map<Long,String> workOrderStageNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<WorkOrderStageEntity> workOrderStageEntityList = workOrderStageService.getStagesByTemplateIdIn(templateIds, corpid, false);
        for (WorkOrderStageEntity entity : workOrderStageEntityList) {
            workOrderStageNameMap.put(entity.getId(), entity.getName());
        }

        for (WorkOrderEntityExt entity : workOrderEntityExts){
            WorkOrderTemplateEntity workOrderTemplateEntity = templateMap.get(entity.getTemplateId());
            //不限时自由工单
            boolean isLimit = Objects.equals(workOrderTemplateEntity.getIsFree(), 1) && Objects.equals(workOrderTemplateEntity.getExpectedTime(), 0);

            JSONObject data = entity.getData();
            data.put(FieldTypeEnum.OWNERID.getAlias(),mainUserMap.getOrDefault(entity.getDataId(),""));
            data.put(FieldTypeEnum.COUSERID.getAlias(),coUserMap.getOrDefault(entity.getDataId(),""));
            //老数据data中没有存阶段状态
            if (data.containsKey(WorkOrderEnum.NODE_STATUS.getAttr()) && Objects.nonNull(data.getInteger(WorkOrderEnum.NODE_STATUS.getAttr()))){
                Integer nodeStatus = data.getInteger(WorkOrderEnum.NODE_STATUS.getAttr());
                if (Objects.isNull(nodeStatus)) {
                    data.put(FieldTypeEnum.WORK_ORDER_NODE_STATUS.getAlias(), "");
                } else {
                    data.put(FieldTypeEnum.WORK_ORDER_NODE_STATUS.getAlias(), WorkOrderNodeStatusEnum.getNameByCode(nodeStatus, ""));
                }
            } else {
                data.put(FieldTypeEnum.WORK_ORDER_NODE_STATUS.getAlias(), "");
            }
            data.put(FieldTypeEnum.WORK_ORDER_STAGE_NAME.getAlias(),workOrderStageNameMap.getOrDefault(entity.getNowStageId(), ""));
            if (isLimit) {
                //data.put(WorkOrderEnum.TIME_OUT.getAttr(), "");
                TimeConsumingOutPojo timeConsumingOutPojo =  workOrderBasicService.workOrderSpecialConsueTime(entity);
                data.put(WorkOrderEnum.TIME_OUT.getAttr(), timeConsumingOutPojo.getConsumeTimeStr());
            } else {
                if (nodeTime){
                    if (nodeMap.size() == 0) {
                        data.put(WorkOrderEnum.TIME_OUT.getAttr(), "");
                    } else {
                        data.put(WorkOrderEnum.TIME_OUT.getAttr(), workOrderBasicService.workOrderNodeConsueTime(nodeMap.get(entity.getId())).getConsumeTimeStr());
                    }
                } else {
                    TimeConsumingOutPojo timeConsumingOutPojo = workOrderBasicService.workOrderConsueTime(entity);
                    data.put(WorkOrderEnum.TIME_OUT.getAttr(), timeConsumingOutPojo.getConsumeTimeStr());
                    if (1 == timeConsumingOutPojo.getIsOut()) {
                        data.put("isRed",1);
                    }
                }
            }
        }
    }


    /**
     * 设置时间筛选条件
     *
     * @param time                    格式（数组：[2016-12-01,2016-12-23]）
     * @param conditionsEntityExtList 条件list
     * @param attr                    要搜索的attr
     * @author lcx
     * @time 2017-1-8 下午3:06:30
     */
    public static void setTimeParam(JSONArray time, List<ConditionsEntityExt> conditionsEntityExtList, String attr) {
        if (time != null && time.size() > 0) {
            String timeStartStr = (String) time.get(0);
            if (time.size() > 1) {
                String timeEndStr = (String) time.get(1);
                Long theTimeEnd = DateTimeUtil.getInt(timeEndStr + " 24:00", DateTimeUtil.SDFYMDHM);
                conditionsEntityExtList.add(EsUtil.packageContions(attr, Arrays.asList(theTimeEnd), ConditionEnum.LESSTHAN, FieldTypeEnum.ADDTIME.getType()));
            }
            Long theTimeStart = DateTimeUtil.getInt(timeStartStr, DateTimeUtil.SDFDate);
            conditionsEntityExtList.add(EsUtil.packageContions(attr, Arrays.asList(theTimeStart), ConditionEnum.GREATEREQUAL, FieldTypeEnum.ADDTIME.getType()));
        }
    }

    /**
     * 获取待采购数量
     * 缺货合同
     * 表单权限，数据权限
     * @param userVO
     * @return
     */
    public Integer getWaitPurchaseCount(UserVO userVO) throws XbbException{
        String corpid = userVO.getCorpid();
        List<PaasFormEntityExt> paasFormEntityExtList = paasFormService.getEnableContractFormList(userVO);
        if (paasFormEntityExtList.isEmpty()){
            return 0;
        }
        List<Long> formIdList = new ArrayList<>();
        for (PaasFormEntityExt entityExt : paasFormEntityExtList){
            formIdList.add(entityExt.getId());
        }
        List<ContractProductEntity> allContractProductList = contractProductModel.getAllContractProduct(corpid, ContractProduceEnum.WAIT_PURCHASE.getCode());
        //每个缺货产品对应的缺货合同订单列表
        Set<Long> dataIdSet = new HashSet<>();
        for (ContractProductEntity entity : allContractProductList) {
            dataIdSet.add(entity.getContractId());
        }
        if (dataIdSet.isEmpty()){
            return 0;
        }
        List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(userVO,userEntity);
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        EsUtil.parseCondition(boolQueryBuilder,conditionsEntityExtList,"",corpid,XbbRefTypeEnum.CONTRACT.getCode());
        boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + ".keyword",corpid));
        boolQueryBuilder.filter(termsQuery(StringConstant.DATA_ID, dataIdSet));
        boolQueryBuilder.filter(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ARCHIVED), ArchivedEnum.UN_ARCHIVED.getCode()));
        boolQueryBuilder.filter(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ALL_OUT_BOUND), AllOutBoundEnum.NON_OUT.getCode()));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
        boolQueryBuilder.filter(termsQuery("formId",formIdList));
        boolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.SHIP_STATUS), ShipStatusEnum.CLOSED.getCode()));
        ElasticAggsPojo elasticAggsPojo = esHelper.elasticAggs(IndexTypeEnum.IDX_SAAS_CONTRACT, boolQueryBuilder, null);
        return StringUtil.toInt(elasticAggsPojo.getTotal(), 0);
    }

    /**
     * 获取待生产数量
     * 缺货合同
     * 表单权限，数据权限
     * @param userVO
     * @return
     */
    public Integer getWaitProduceCount(UserVO userVO) throws XbbException {
        String corpid = userVO.getCorpid();
        List<PaasFormEntityExt> paasFormEntityExtList = paasFormService.getEnableContractFormList(userVO);
        if (paasFormEntityExtList.isEmpty()){
            return 0;
        }
        List<Long> formIdList = new ArrayList<>();
        for (PaasFormEntityExt entityExt : paasFormEntityExtList){
            formIdList.add(entityExt.getId());
        }
        List<ContractProductEntity> allContractProductList = contractProductModel.getAllContractProduct(corpid, ContractProduceEnum.WAIT_PRODUCE.getCode());
        //每个缺货产品对应的缺货合同订单列表
        Set<Long> dataIdSet = new HashSet<>();
        for (ContractProductEntity entity : allContractProductList) {
            dataIdSet.add(entity.getContractId());
        }
        if (dataIdSet.isEmpty()){
            return 0;
        }
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(userVO,userEntity);
        List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>();
//        saasListDataPermissionHelp.listDataPermission(conditionsEntityExtList,userEntity,XbbRefTypeEnum.CONTRACT.getCode(),XbbRefTypeEnum.CONTRACT.getCode());
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        EsUtil.parseCondition(boolQueryBuilder,conditionsEntityExtList,"",corpid,XbbRefTypeEnum.CONTRACT.getCode());
        boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + ".keyword",corpid));
        boolQueryBuilder.filter(termsQuery(StringConstant.DATA_ID, dataIdSet));
        boolQueryBuilder.filter(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ARCHIVED), ArchivedEnum.UN_ARCHIVED.getCode()));
        boolQueryBuilder.filter(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ALL_OUT_BOUND), AllOutBoundEnum.NON_OUT.getCode()));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
        boolQueryBuilder.filter(termsQuery("formId",formIdList));
        boolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.SHIP_STATUS), ShipStatusEnum.CLOSED.getCode()));
        ElasticAggsPojo elasticAggsPojo = esHelper.elasticAggs(IndexTypeEnum.IDX_SAAS_CONTRACT, boolQueryBuilder, null);
        return StringUtil.toInt(elasticAggsPojo.getTotal(), 0);
    }

    /**
     * 获取待入库数量
     * 采购合同
     * 数据权限
     * @param userVO
     * @return
     */
    public Integer getWaitInstock(UserVO userVO) throws XbbException {
        String corpid = userVO.getCorpid();
        List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(userVO,userEntity);
//        saasListDataPermissionHelp.listDataPermission(conditionsEntityExtList,userEntity,XbbRefTypeEnum.CONTRACT.getCode(),XbbRefTypeEnum.CONTRACT.getCode());
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        EsUtil.parseCondition(boolQueryBuilder,conditionsEntityExtList,"",corpid,XbbRefTypeEnum.CONTRACT.getCode());
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery("data." + PurchaseEnum.ALL_INCOMING.getAttr(), AllInBoundEnum.NON_IN.getCode()));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        boolQueryBuilder.mustNot(termQuery(PurchaseEnum.getEsAttr4Keyword(PurchaseEnum.RECEIVE_STATUS), ReceiveStatusEnum.CLOSED.getCode()));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
        List<IndexBoost> indexBoosts = new ArrayList<>(1);
        indexBoosts.add(new IndexBoost(IndexTypeEnum.IDX_SAAS_PURCHASE.getIndex(),0));
        nativeSearchQueryBuilder.withIndicesBoost(indexBoosts);
        ElasticAggsPojo elasticAggsPojo = esHelper.elasticAggs(IndexTypeEnum.IDX_SAAS_PURCHASE, boolQueryBuilder, null);
        return StringUtil.toInt(elasticAggsPojo.getTotal(), 0);
    }

    /**
     * 获取待出库数量
     * 销售合同
     * 表单权限，数据权限
     * @param userVO
     * @return
     */
    public Integer getWaitOutstock(UserVO userVO,Integer distributorMark) throws XbbException {
        String corpid = userVO.getCorpid();
        List<PaasFormEntityExt> paasFormEntityExtList = paasFormService.getEnableContractFormListDistributor(userVO,distributorMark);
        if (paasFormEntityExtList.isEmpty()){
            return 0;
        }
        List<Long> formIdList = new ArrayList<>();
        for (PaasFormEntityExt entityExt : paasFormEntityExtList){
            formIdList.add(entityExt.getId());
        }
        List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(userVO,userEntity);
//        saasListDataPermissionHelp.listDataPermission(conditionsEntityExtList,userVO,XbbRefTypeEnum.CONTRACT.getCode(),XbbRefTypeEnum.CONTRACT.getCode());
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        EsUtil.parseCondition(boolQueryBuilder,conditionsEntityExtList,"",corpid,XbbRefTypeEnum.CONTRACT.getCode());
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery("data." + ContractEnum.ALL_OUT_BOUND.getAttr(), AllOutBoundEnum.NON_OUT.getCode()));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery("data." + ContractEnum.ARCHIVED.getAttr(), ArchivedEnum.UN_ARCHIVED.getCode()));
        boolQueryBuilder.filter(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.IS_RED), 0));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
        boolQueryBuilder.filter(termsQuery("formId",formIdList));
        boolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.SHIP_STATUS), ShipStatusEnum.CLOSED.getCode()));
        if (Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())){
            boolQueryBuilder.filter(termQuery("data." + OrderEnum.STATUS.getAttr(), OrderStatusEnum.DELIVERED.getCode()));
        }
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
//        nativeSearchQueryBuilder.withIndices(IndexTypeEnum.IDX_SAAS_CONTRACT.getIndex()).withTypes(IndexTypeEnum.IDX_SAAS_CONTRACT.getType());
        List<IndexBoost> indexBoosts = new ArrayList<>(1);
        indexBoosts.add(new IndexBoost(IndexTypeEnum.IDX_SAAS_CONTRACT.getIndex(),0));
        nativeSearchQueryBuilder.withIndicesBoost(indexBoosts);
        ElasticAggsPojo elasticAggsPojo = esHelper.elasticAggs(IndexTypeEnum.IDX_SAAS_CONTRACT, boolQueryBuilder, null);
        return StringUtil.toInt(elasticAggsPojo.getTotal(), 0);
    }

    public Long getWaitRob(UserVO loginUser) throws XbbException{
        List<ConditionsEntityExt> conditionsList = new ArrayList<>();
        workOrderListDataPermissionHelp.robListDataPermission(conditionsList, loginUser, loginUser.getDepSet());
        // 加模板过滤，没有查看权限的模板不统计
        List<WorkOrderFormEntity> workOrderFormEntityList = workOrderFormService.getTemplateWithPermission(loginUser, null, 0);
        List<Long> formIds = new ArrayList<>();
        for (WorkOrderFormEntity entity : workOrderFormEntityList) {
            formIds.add(entity.getId());
        }
        if (formIds.isEmpty()){
            return 0L;
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", loginUser.getCorpid()));
        boolQueryBuilder.filter(termQuery(FieldTypeEnum.WORK_ORDER_ROB.getAlias(), WorkOrderTypeEnum.ROB.getCode()));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery("formId", formIds));
        boolQueryBuilder.filter(termsQuery("flowStatus", FlowStatusEnum.getStatisticType()));
        EsUtil.parseCondition(boolQueryBuilder, conditionsList, "", loginUser.getCorpid(), XbbRefTypeEnum.WORK_ORDER.getCode());
        ElasticAggsPojo elasticAggsPojo = esHelper.elasticAggs(IndexTypeEnum.IDX_SAAS_WORK_ORDER, boolQueryBuilder, null);
        return Long.valueOf(elasticAggsPojo.getTotal());
    }

    /**
     * 设置呼叫电话
     *
     * @param userEntity        用户
     * @param explainMap 解释
     * @param customer          客户
     * @param others            其他
     * @throws XbbException
     * @author long.rao
     * @date 2019-03-22 13:52
     */
    public void setCallPhone(UserEntity userEntity, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt customer, JSONObject others) throws XbbException {
        AliyunCall.setCallPhone(userEntity.getCorpid(), esHelper, explainMap, customer, others);
    }

    /**
     * 设置呼叫电话
     *
     * @param userEntity        用户
     * @param explainMap 解释
     * @param customer          客户
     * @throws XbbException
     * @author long.rao
     * @date 2019-03-22 13:52
     */
    public boolean checkShowCall(UserEntity userEntity, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt customer) throws XbbException {
        String corpid = userEntity.getCorpid();
        return AliyunCall.checkShowCall(corpid, explainMap, customer);
    }

    /**
     * 设置呼叫电话（线索电话只有自己）
     *
     * @param userEntity        用户
     * @param explainMap 解释
     * @param clue          线索
     * @param others            其他
     * @throws XbbException
     * @author youli.chen
     * @date 2021-01-11 13:52
     */
    public void setClueCallPhone(UserEntity userEntity, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt clue, JSONObject others, String creatorId, UserVO loginUser) throws XbbException {
        String corpid = userEntity.getCorpid();
        JSONObject data = clue.getData();
        Long clueId = clue.getDataId();
        JSONArray cluePhoneArray = FastJsonHelper.getJsonArrFromFormData(data, ClueEnum.PHONE.getAttr());
        if (cluePhoneArray == null || cluePhoneArray.isEmpty()) {
            //没有电话，直接返回
            return;
        }
        //电话可见判断
        boolean phoneCanSee = formDataValidateProductHelp.attrCanSee(explainMap.get(ClueEnum.PHONE.getAttr()),clueId,creatorId,loginUser,corpid,XbbRefTypeEnum.CLUE.getCode());

        JSONArray clueArr = new JSONArray();
        for (int i = 0; i < cluePhoneArray.size(); i++) {
            JSONObject clueObj = new JSONObject();
            JSONObject item = cluePhoneArray.getJSONObject(i);
            String tel = item.getString(StringConstant.PHONE_TEL_ATTR);
            clueObj.put("id", clueId);
            clueObj.put("refType", XbbRefTypeEnum.CLUE.getCode());
            clueObj.put("name", data.getOrDefault(ClueEnum.COMPANY_NAME.getAttr(), ""));
            clueObj.put("telNum", tel);
            if (tel != null) {
                if (!Objects.equals(tel, "")) {
                    clueObj.put("phoneNum", tel);
                    if (!phoneCanSee) {
                        String telNum = "";
                        if (tel.length() > 5) {
                            telNum = tel.substring(0, 3) + "****" + tel.substring(tel.length() - 2);
                        } else {
                            telNum = StringConstant.INVISIBLE_VALUE;
                        }
                        clueObj.put("telNum", telNum);
                    }
                } else if (Objects.equals(tel, "")) {
                    clueObj.put("phoneNum", "");
                }
            }
            clueArr.add(clueObj);
        }
        if (!clueArr.isEmpty()) {
            // 前端暂时共用，后端命名暂时不改
            others.put("customerDial", clueArr);
        }
        //前端用于判断呼叫中心相关
        others.put("isCallCenter", true);
    }


    public List<AggSumVO> avgBySumList(List<AggSumVO> numCountList, FormDataSummaryDTO formDataSummaryDTO, List<AggSumDTO> aggAvgFieldList, NativeSearchQuery searchQuery) throws XbbException {
        List<AggSumVO> aggAvgList = new ArrayList<>();
        Integer businessType = formDataSummaryDTO.getBusinessType();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        switch (xbbRefTypeEnum) {
            case CONTRACT:
                aggAvgList = contractService.avgBySumList(numCountList, formDataSummaryDTO, aggAvgFieldList, searchQuery);
                break;
            case SALES_OPPORTUNITY:
                aggAvgList = opportunityService.aggAvgByField(numCountList, formDataSummaryDTO, aggAvgFieldList);
                break;
            case QUOTATION:
                aggAvgList = quotationService.aggAvgByField(numCountList, formDataSummaryDTO, aggAvgFieldList, searchQuery);
                break;
            default:
                break;
        }
        return aggAvgList;
    }

    /**
     * 封装分组条件
     * 列表、汇总、筛选、附近客户、产品、工单
     * 列表、汇总、筛选会有公海分组、且需要formId
     * @param formDataListDTO
     * @param groupConditionList
     * @param shouldConditionList
     * @return
     * @throws XbbException
     */
    public void packageGroupList(FormDataListDTO formDataListDTO,List<ConditionsEntityExt> groupConditionList,List<List<ConditionsEntityExt>> shouldConditionList) throws XbbException{
        String corpid = formDataListDTO.getCorpid();
        Integer defaultGroup = formDataListDTO.getDefaultGroup();
        Long listGroupId = formDataListDTO.getListGroupId();
        Integer businessType = formDataListDTO.getBusinessType();
        if (listGroupId != null || Objects.equals(defaultGroup, 2)) {
            PaasListGroupEntity paasListGroupEntity;
            if (Objects.equals(defaultGroup, 1)) {
                if (Objects.equals(businessType,XbbRefTypeEnum.WORK_ORDER.getCode())){
                    paasListGroupEntity = workOrderListGroupHelp.getDefaultGroup(formDataListDTO);
                }else {
                    paasListGroupEntity = listGroupHelp.getDefaultGroup(formDataListDTO);
                }
            } else if (Objects.equals(formDataListDTO.getDefaultGroup(), 2)) {
                ConditionListPojo conditionListPojo = new ConditionListPojo(formDataListDTO.getCorpid(), formDataListDTO.getFormId(), formDataListDTO.getBusinessType(), formDataListDTO.getListGroupId(), formDataListDTO.getDefaultGroup(), formDataListDTO.getConditions(), shouldConditionList, formDataListDTO.getLoginUser(), formDataListDTO.getPlatform(), formDataListDTO.getSubBusinessType(), formDataListDTO.getStatusFilter(), formDataListDTO.getCommonFilter(), formDataListDTO.getStatisticsType());
                GroupConditionPoJo groupConditionPoJo = publicGroupHelp.getPublicGroup(conditionListPojo);
                paasListGroupEntity = groupConditionPoJo.getPaasListGroupEntity();
                shouldConditionList.addAll(formDataListDTO.getShouldConditions());
            } else {
                paasListGroupEntity = paasListGroupModel.getByKey(listGroupId, corpid);
            }
            if (paasListGroupEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.LIST_GROUP_NOT_EXIST);
            }
            List<ConditionsEntityExt> listGroupConditionList = JSONArray.parseArray(paasListGroupEntity.getJsonData(), ConditionsEntityExt.class);
            if (listGroupConditionList != null && !listGroupConditionList.isEmpty()) {
                //conditionList筛选条件
                //分组条件加入到conditionList中
                groupConditionList.addAll(listGroupConditionList);
            }
        }
    }

    private List<ConditionsEntityExt> packageCustomerIndexCondition(Integer statusFilter){
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        if (!(Objects.isNull(statusFilter) || statusFilter == 0)){
            ConditionsEntityExt statusFilterEntityExt = new ConditionsEntityExt();
            statusFilterEntityExt.setAttr(CustomerManagementEnum.IS_ARCHIVED.getAttr());
            statusFilterEntityExt.setFieldType(CustomerManagementEnum.IS_ARCHIVED.getFieldType());
            statusFilterEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            statusFilterEntityExt.setValue(Collections.singletonList(statusFilter));
            conditionList.add(statusFilterEntityExt);
        }
        return conditionList;
    }

    private List<ConditionsEntityExt> packageCustomerCondition(Integer subBusinessType, String corpid, String userId,Integer statusFilter){
        UserVO userVO = new UserVO();
        userVO.setUserId(userId);
        ConditionListPojo conditionListPojo = new ConditionListPojo(subBusinessType, corpid, userVO, statusFilter, null);
        return customerConditionService.packageConditionBySubBusinessType(conditionListPojo);
    }

    private List<ConditionsEntityExt> packageClueCondition(Integer subBusinessType, String corpid, String userId,Integer statusFilter){
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        Integer isPublic = 0;
        if (Objects.equals(subBusinessType,XbbRefTypeEnum.CLUE_PUBLIC.getCode())) {
            isPublic = 1;
        }
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setAttr(ClueEnum.IS_PUBLIC.getAttr());
        conditionsEntityExt.setFieldType(ClueEnum.IS_PUBLIC.getFieldType());
        conditionsEntityExt.setName(ClueEnum.IS_PUBLIC.getAttrName());
        conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
        conditionsEntityExt.setValue(Collections.singletonList(isPublic));
        conditionList.add(conditionsEntityExt);
        if (!Objects.equals(subBusinessType,XbbRefTypeEnum.CLUE_PUBLIC.getCode()) && !(Objects.isNull(statusFilter) || statusFilter == 0)){
            ConditionsEntityExt statusFilterEntityExt = new ConditionsEntityExt();
            statusFilterEntityExt.setAttr(ClueEnum.IS_ARCHIVED.getAttr());
            statusFilterEntityExt.setFieldType(ClueEnum.IS_ARCHIVED.getFieldType());
            statusFilterEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            statusFilterEntityExt.setValue(Collections.singletonList(statusFilter));
            conditionList.add(statusFilterEntityExt);
        }
        return conditionList;
    }

    private List<ConditionsEntityExt> packageOpportunityCondition(Integer subBusinessType, String corpid, String userId,Integer statusFilter) {
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(subBusinessType);
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        if (xbbRefTypeEnum == XbbRefTypeEnum.KEY_OPPORTUNITY) {
            boolean isShare;
            try {
                isShare = companyConfigModel.hasBeenEnable(corpid, CompanyConfigEnum.SHARE_FOCUS_OPPORTUNITY.getAlias(), BasicConstant.IS_USE.toString());
            } catch (XbbException e) {
                isShare = Objects.equals(CompanyConfigEnum.SHARE_FOCUS_OPPORTUNITY.getValue(), BasicConstant.IS_USE.toString());
            }
            List<Long> dataIdList;
            if (isShare) {
                dataIdList = opportunityFocusModel.getShareOpportunityIdList(corpid);
            } else {
                dataIdList = opportunityFocusModel.getNoShareOpportunityIdList(userId, corpid);
            }
            dataIdList.add(-1L);
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setAttr(FieldTypeEnum.DATAID.getAlias());
            conditionsEntityExt.setFieldType(FieldTypeEnum.DATAID.getType());
            conditionsEntityExt.setName(FieldTypeEnum.DATAID.getDescription());
            conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
            conditionsEntityExt.setValue(new ArrayList<>(dataIdList));
            conditionList.add(conditionsEntityExt);
        }
        if (!(Objects.isNull(statusFilter) || statusFilter == 0)){
            ConditionsEntityExt statusFilterEntityExt = new ConditionsEntityExt();
            statusFilterEntityExt.setAttr(SalesOpportunityEnum.IS_ARCHIVED.getAttr());
            statusFilterEntityExt.setFieldType(SalesOpportunityEnum.IS_ARCHIVED.getFieldType());
            statusFilterEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            statusFilterEntityExt.setValue(Collections.singletonList(statusFilter));
            conditionList.add(statusFilterEntityExt);
        }
        return conditionList;
    }

    public List<ConditionsEntityExt> packageConditionBySubBusinessType(Integer subBusinessType, String corpid, String userId, Integer statusFilter){
        if (Objects.isNull(subBusinessType)){
            return new ArrayList<>();
        }
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(subBusinessType);
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        UserVO userVO = new UserVO();
        userVO.setUserId(userId);
        ConditionListPojo conditionListPojo = new ConditionListPojo(subBusinessType, corpid, userVO, statusFilter, null);
        BusinessConditionService businessPermissionService = businessConditionMap.get(subBusinessType);
        switch (xbbRefTypeEnum){
            case CUSTOMER_MANAGEMENT:
            case CUSTOMER:
            case CUSTOMER_DEAL:
            case CUSTOMER_FOCUS:
            case CUSTOMER_FOLLOW:
            case CUSTOMER_PUBLIC:
            case SALES_OPPORTUNITY:
            case ALL_OPPORTUNITY:
            case KEY_OPPORTUNITY:
            case CONTRACT:
            case ORDER:
                conditionList = businessPermissionService.packageConditionBySubBusinessType(conditionListPojo);
                break;
            case CUSTOMER_INDEX:
                conditionList.addAll(packageCustomerIndexCondition(statusFilter));
                break;
            case INVOICE:
                conditionList.addAll(packageInvoiceCondition(statusFilter));
                break;
            case PURCHASE_INVOICE:
                conditionList.addAll(packagePurchaseInvoiceCondition(statusFilter));
                break;
            case WORK_ORDER:
                conditionList.addAll(packageWorkOrderCondition());
                break;
            case WORK_ORDER_ROB:
                conditionList.addAll(packageWorkOrderRobCondition());
                break;
            case QUOTATION:
                conditionList.addAll(packageQuotationCondition(statusFilter));
                break;
            case PAYMENT_SHEET:
                conditionList.addAll(packagePaymentAndPaySheetCondition());
                break;
            case PAY_SHEET:
                conditionList.addAll(packagePaymentAndPaySheetCondition());
                break;
            case CUSTOMER_STATEMENT_STATISTIC:
                conditionList.addAll(statementCondition(statusFilter));
                break;
            case CLUE:
            case ALL_CLUE:
            case CLUE_PUBLIC:
                conditionList.addAll(packageClueCondition(subBusinessType,corpid,userId,statusFilter));
                break;
            //todo  qcy  目前还没有发现要特殊处理的，先占个位置
            case MARKET_ACTIVITY:
                conditionList.addAll(packageMarketActivityCondition());
                break;
            case COST_ADJUST:
                conditionList.addAll(packageMarketActivityCondition());
                break;
            default:
                break;
        }
        return conditionList;
    }

    private List<ConditionsEntityExt> packageWorkOrderRobCondition() {
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        ConditionsEntityExt  conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setAttr(FieldTypeEnum.WORK_ORDER_ROB.getAlias());
        conditionsEntityExt.setFieldType(FieldTypeEnum.WORK_ORDER_ROB.getType());
        conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
        conditionsEntityExt.setValue(Collections.singletonList(WorkOrderTypeEnum.ROB.getCode()));
        conditionList.add(conditionsEntityExt);
        return conditionList;
    }

    private List<ConditionsEntityExt> packageWorkOrderCondition() {
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setAttr(FieldTypeEnum.WORK_ORDER_ROB.getAlias());
        conditionsEntityExt.setFieldType(FieldTypeEnum.WORK_ORDER_ROB.getType());
        conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
        conditionsEntityExt.setValue(Collections.singletonList(WorkOrderTypeEnum.NORMAL.getCode()));
        conditionList.add(conditionsEntityExt);
        return conditionList;
    }

    private List<ConditionsEntityExt> packageInvoiceCondition(Integer statusFilter) {
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        if (Objects.equals(statusFilter,BasicConstant.ONE)){
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setAttr(InvoiceEnum.IS_RED.getAttr());
            conditionsEntityExt.setFieldType(FieldTypeEnum.NUM.getType());
            conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            conditionsEntityExt.setValue(Collections.singletonList(1));
            conditionList.add(conditionsEntityExt);
        }else if (Objects.equals(statusFilter,BasicConstant.TWO)){
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setAttr(InvoiceEnum.IS_CANCEL.getAttr());
            conditionsEntityExt.setFieldType(FieldTypeEnum.NUM.getType());
            conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            conditionsEntityExt.setValue(Collections.singletonList(1));
            conditionList.add(conditionsEntityExt);
        }else if(Objects.equals(statusFilter,BasicConstant.THREE)) {
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setAttr(InvoiceEnum.IS_CANCEL.getAttr());
            conditionsEntityExt.setFieldType(FieldTypeEnum.NUM.getType());
            conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            conditionsEntityExt.setValue(Collections.singletonList(0));
            ConditionsEntityExt conditionsEntityExt2 = new ConditionsEntityExt();
            conditionsEntityExt2.setAttr(InvoiceEnum.IS_RED.getAttr());
            conditionsEntityExt2.setFieldType(FieldTypeEnum.NUM.getType());
            conditionsEntityExt2.setSymbol(ConditionEnum.EQUAL.getSymbol());
            conditionsEntityExt2.setValue(Collections.singletonList(0));
            conditionList.add(conditionsEntityExt);
            conditionList.add(conditionsEntityExt2);
        }
        return conditionList;
    }

    private List<ConditionsEntityExt> packagePurchaseInvoiceCondition(Integer statusFilter) {
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        if (Objects.equals(statusFilter,BasicConstant.ONE)){
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setAttr(PurchaseInvoiceEnum.IS_RED.getAttr());
            conditionsEntityExt.setFieldType(FieldTypeEnum.NUM.getType());
            conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            conditionsEntityExt.setValue(Collections.singletonList(1));
            conditionList.add(conditionsEntityExt);
        }else if (Objects.equals(statusFilter,BasicConstant.TWO)){
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setAttr(PurchaseInvoiceEnum.IS_CANCEL.getAttr());
            conditionsEntityExt.setFieldType(FieldTypeEnum.NUM.getType());
            conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            conditionsEntityExt.setValue(Collections.singletonList(1));
            conditionList.add(conditionsEntityExt);
        }else if(Objects.equals(statusFilter,BasicConstant.THREE)) {
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setAttr(PurchaseInvoiceEnum.IS_CANCEL.getAttr());
            conditionsEntityExt.setFieldType(FieldTypeEnum.NUM.getType());
            conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            conditionsEntityExt.setValue(Collections.singletonList(0));
            ConditionsEntityExt conditionsEntityExt2 = new ConditionsEntityExt();
            conditionsEntityExt2.setAttr(PurchaseInvoiceEnum.IS_RED.getAttr());
            conditionsEntityExt2.setFieldType(FieldTypeEnum.NUM.getType());
            conditionsEntityExt2.setSymbol(ConditionEnum.EQUAL.getSymbol());
            conditionsEntityExt2.setValue(Collections.singletonList(0));
            conditionList.add(conditionsEntityExt);
            conditionList.add(conditionsEntityExt2);
        }
        return conditionList;
    }

    private List<ConditionsEntityExt> packageQuotationCondition(Integer statusFilter) {
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        // 报价单列表展示最新版本的报价单
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setAttr(QuotationEnum.IS_NEW.getAttr());
        conditionsEntityExt.setFieldType(FieldTypeEnum.NUM.getType());
        conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
        conditionsEntityExt.setValue(Collections.singletonList(BasicConstant.ONE));
        conditionList.add(conditionsEntityExt);
        if (!(Objects.isNull(statusFilter) || statusFilter == 0)){
            ConditionsEntityExt statusFilterEntityExt = new ConditionsEntityExt();
            statusFilterEntityExt.setAttr(QuotationEnum.ARCHIVED.getAttr());
            statusFilterEntityExt.setFieldType(QuotationEnum.ARCHIVED.getFieldType());
            statusFilterEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            statusFilterEntityExt.setValue(Collections.singletonList(statusFilter));
            conditionList.add(statusFilterEntityExt);
        }
        return conditionList;
    }

    private List<ConditionsEntityExt> statementCondition(Integer statusFilter) {
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        if ((Objects.nonNull(statusFilter) && statusFilter != 0)) {
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setAttr(CustomerStatementStatisticEnum.IS_ARCHIVED.getAttr());
            conditionsEntityExt.setFieldType(FieldTypeEnum.COMBO_NUM.getType());
            conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            conditionsEntityExt.setValue(Collections.singletonList(statusFilter));
            conditionList.add(conditionsEntityExt);
        }
        return conditionList;
    }

    private List<ConditionsEntityExt> packagePaymentAndPaySheetCondition() {
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setAttr(FieldTypeEnum.SHEET_ALONE.getAlias());
        conditionsEntityExt.setFieldType(FieldTypeEnum.SHEET_ALONE.getType());
        conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
        conditionsEntityExt.setValue(Arrays.asList(SheetAloneEnum.NORMAL.getCode(), SheetAloneEnum.PARENT.getCode()));
        conditionList.add(conditionsEntityExt);
        return conditionList;
    }

    private List<ConditionsEntityExt> packageContractCondition(Integer statusFilter) {
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setAttr(ContractEnum.IS_RED.getAttr());
        conditionsEntityExt.setFieldType(ContractEnum.IS_RED.getFieldType());
        conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
        conditionsEntityExt.setValue(Collections.singletonList(0));
        conditionList.add(conditionsEntityExt);
        if (!(Objects.isNull(statusFilter) || statusFilter == 0)){
            ConditionsEntityExt statusFilterEntityExt = new ConditionsEntityExt();
            statusFilterEntityExt.setAttr(ContractEnum.ARCHIVED.getAttr());
            statusFilterEntityExt.setFieldType(ContractEnum.ARCHIVED.getFieldType());
            statusFilterEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            statusFilterEntityExt.setValue(Collections.singletonList(statusFilter));
            conditionList.add(statusFilterEntityExt);
        }
        return conditionList;
    }
    private List<ConditionsEntityExt> packageMarketActivityCondition() {
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
//        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
//        conditionsEntityExt.setAttr(FieldTypeEnum.SHEET_ALONE.getAlias());
//        conditionsEntityExt.setFieldType(FieldTypeEnum.SHEET_ALONE.getType());
//        conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
//        conditionsEntityExt.setValue(Arrays.asList(SheetAloneEnum.NORMAL.getCode(), SheetAloneEnum.PARENT.getCode()));
//        conditionList.add(conditionsEntityExt);
        return conditionList;
    }

    public Integer packageDelCondition(Integer subBusinessType) {
        if (Objects.equals(XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode(),subBusinessType) || Objects.equals(XbbRefTypeEnum.CLUE_RECYCLE.getCode(),subBusinessType)){
            return 1;
        }
        return 0;
    }

    /**
     * 电话获取
     * @param dataList
     * @param businessType
     * @param corpid
     * @return
     * @throws XbbException
     */
    public List<DetaPhonePojo> cusCallPhone(JSONObject dataList, Integer businessType, String corpid, Map<String, FieldAttrEntity> explainMap, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        return callCenterService.cusCallPhone(dataList, businessType, corpid, explainMap, handlerExplainDTO);
    }

    /**
     * 地址筛选条件
     *
     * @param formDataListDTO 参数
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-07-05 09:17
     * @since v1.0
     * @version v1.0
     */
    public void addressSearchCondition(FormDataListDTO formDataListDTO) {
       List<ConditionsEntityExt> conditions = formDataListDTO.getConditions();
       AddressUtil.addressSearchCondition(conditions, formDataListDTO.getShouldConditions());
       formDataListDTO.setConditions(conditions);
    }


    public void addressSearchShouldCondition(FormDataListDTO formDataListDTO) {
        AddressUtil.addressSearchShouldCondition(formDataListDTO.getShouldConditions());
    }
    /**
     * 常用筛选封装查询条件
     * @param searchDataInConditionDTO
     * @throws XbbException
     */
    public void packageSearchDataCondition(SearchDataInConditionDTO searchDataInConditionDTO) throws XbbException {
        String corpid = searchDataInConditionDTO.getCorpid();
        Integer forChart = searchDataInConditionDTO.getForChart();
        Integer forScore = searchDataInConditionDTO.getForScore();
        List<ConditionsEntityExt> groupConditionsList = new ArrayList<>();
        List<List<ConditionsEntityExt>> shouldCondition = new ArrayList<>();
        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(searchDataInConditionDTO,formDataListDTO);
        formDataListSearchHelp.filterApprovalData(formDataListDTO);
        searchDataInConditionDTO.getConditionsList().addAll(formDataListDTO.getConditions());
        packageGroupList(formDataListDTO,groupConditionsList,shouldCondition);
        searchDataInConditionDTO.getConditionsList().addAll(groupConditionsList);
        searchDataInConditionDTO.getShouldConditionsList().addAll(shouldCondition);
        if (Objects.equals(searchDataInConditionDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
            List<ConditionsEntityExt> subConditionList = packageConditionBySubBusinessType(searchDataInConditionDTO.getSubBusinessType(),corpid,searchDataInConditionDTO.getUserId(), searchDataInConditionDTO.getStatusFilter());
            searchDataInConditionDTO.getConditionsList().addAll(subConditionList);
            if (Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.WORK_ORDER.getCode())){
                if (Objects.equals(searchDataInConditionDTO.getFormId(), 0L)) {
                    //工单全部列表特殊处理
                    List<WorkOrderFormEntity> workOrderFormEntityList = workOrderFormService.getTemplateWithPermission(formDataListDTO.getLoginUser(), formDataListDTO.getAppId(), null);
                    List<Long> formIds = new ArrayList<>();
                    for (WorkOrderFormEntity entity : workOrderFormEntityList) {
                        formIds.add(entity.getId());
                    }
                    searchDataInConditionDTO.setFormIdList(formIds);
                    searchDataInConditionDTO.setLimitForms(true);
                }
                if (Objects.equals(searchDataInConditionDTO.getSubBusinessType(), XbbRefTypeEnum.WORK_ORDER_ROB.getCode())) {
                    //工单待抢单过滤正常列表数据
                    ConditionsEntityExt  conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(FieldTypeEnum.WORK_ORDER_ROB.getAlias());
                    conditionsEntityExt.setFieldType(FieldTypeEnum.WORK_ORDER_ROB.getType());
                    conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    conditionsEntityExt.setValue(Collections.singletonList(WorkOrderTypeEnum.ROB.getCode()));
                    searchDataInConditionDTO.getConditionsList().add(conditionsEntityExt);
                }
                if(!Objects.equals(1,forChart) && !Objects.equals(1,forScore)){
                    workOrderListDataPermissionHelp.listDataPermission(searchDataInConditionDTO.getConditionsList(),searchDataInConditionDTO.getShouldConditionsList(),searchDataInConditionDTO.getLoginUser(),searchDataInConditionDTO.getDefaultGroup(),searchDataInConditionDTO.getListGroupId());
                }
            }else if (Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.WORK_ORDER_V2.getCode())){
                if (Objects.equals(searchDataInConditionDTO.getFormId(), 0L)) {
                    //工单全部列表特殊处理
                    List<PaasFormEntityExt> workOrderFormEntityList = paasFormModel.getEnableFormList(formDataListDTO.getCorpid(), XbbRefTypeEnum.WORK_ORDER_V2.getCode());
                    paasFormModel.removeByPermission(workOrderFormEntityList, formDataListDTO.getLoginUser());
                    List<Long> formIds = new ArrayList<>();
                    for (PaasFormEntityExt entity : workOrderFormEntityList) {
                        formIds.add(entity.getId());
                    }
                    searchDataInConditionDTO.setFormIdList(formIds);
                    searchDataInConditionDTO.setLimitForms(true);
                }
                if (Objects.nonNull(searchDataInConditionDTO.getPoolId()) && Objects.equals(XbbRefTypeEnum.WORK_ORDER_V2_POOL.getCode(), searchDataInConditionDTO.getSubBusinessType())) {
                    ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt("text_7", "", FieldTypeEnum.COMBO.getType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(searchDataInConditionDTO.getPoolId()));
                    searchDataInConditionDTO.getConditionsList().add(conditionsEntityExt);
                    ConditionsEntityExt statusEntityExt = new ConditionsEntityExt("text_4","",FieldTypeEnum.COMBO.getType(),ConditionEnum.EQUAL.getSymbol(), Collections.singletonList("1"));
                    ConditionsEntityExt isPool = new ConditionsEntityExt("num_6","", FieldTypeEnum.NUM.getType(),ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(1));
                    searchDataInConditionDTO.getConditionsList().add(statusEntityExt);
                    searchDataInConditionDTO.getConditionsList().add(isPool);
                } else if (Objects.equals(XbbRefTypeEnum.WORK_ORDER_V2_APPOINT.getCode(), searchDataInConditionDTO.getSubBusinessType())) {
                    List<Object> nodeIdList = new ArrayList<>();
                    nodeIdList.add("2");
                    ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt("text_15", "", FieldTypeEnum.COMBO.getType(), ConditionEnum.EQUAL.getSymbol(), nodeIdList);
                    searchDataInConditionDTO.getConditionsList().add(conditionsEntityExt);
                    List<ConditionsEntityExt> poolConditionList = new ArrayList<>();
                    ConditionsEntityExt inPoolCondition = new ConditionsEntityExt("num_6", "", FieldTypeEnum.NUM.getType(), ConditionEnum.IN.getSymbol(), Collections.singletonList(1));
                    poolConditionList.add(inPoolCondition);
                    List<ConditionsEntityExt> userTeamList = new ArrayList<>();
                    saasListDataPermissionHelp.listDataPermission(userTeamList, searchDataInConditionDTO.getLoginUser(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSubBusinessType());
                    searchDataInConditionDTO.getShouldConditionsList().add(poolConditionList);
                    searchDataInConditionDTO.getShouldConditionsList().add(userTeamList);
                } else {
                    saasListDataPermissionHelp.listDataPermission(searchDataInConditionDTO.getConditionsList(), searchDataInConditionDTO.getLoginUser(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSubBusinessType());
                }

            }else if (Objects.equals(searchDataInConditionDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_PURCHASE.getCode())){
                if (!(Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(),searchDataInConditionDTO.getBusinessType()) && Objects.equals(searchDataInConditionDTO.getAttr(),ProductEnum.SUPPLIER.getAttr()))){
                    searchDataInConditionDTO.getConditionsList().addAll(packageWaitPurchaseCondition(formDataListDTO));
                    searchDataInConditionDTO.getShouldConditionsList().addAll(formDataListDTO.getShouldConditions());
                    // 合同视图将所有启用的合同模版id都放入筛选条件
                    String columns = "id";
                    Map<String,Object> map = new HashMap<>();
                    map.put("corpid", corpid);
                    map.put("businessType", XbbRefTypeEnum.CONTRACT.getCode());
                    map.put("del", 0);
                    map.put("enable",1);
                    map.put("columns","id");
                    List<PaasFormEntity> entity = paasFormModel.findEntity(map);
                    List<Long> formIdList = new ArrayList<>();
                    formIdList.add(formDataListDTO.getFormId());
                    if (CollectionUtils.isNotEmpty(entity)){
                        entity.forEach(item -> formIdList.add(item.getId()));
                    }
                    searchDataInConditionDTO.setFormIdList(formIdList);
                    searchDataInConditionDTO.setLimitForms(formDataListDTO.getLimitForms());
                }
            }else if (Objects.equals(searchDataInConditionDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_PRODUCE.getCode())){
                if (!(Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(),searchDataInConditionDTO.getBusinessType()) && Objects.equals(searchDataInConditionDTO.getAttr(),ProductEnum.SUPPLIER.getAttr()))) {
                    searchDataInConditionDTO.getConditionsList().addAll(packageWaitProduceCondition(formDataListDTO));
                    searchDataInConditionDTO.getShouldConditionsList().addAll(formDataListDTO.getShouldConditions());
                    searchDataInConditionDTO.setFormIdList(formDataListDTO.getFormIdList());
                    searchDataInConditionDTO.setLimitForms(formDataListDTO.getLimitForms());
                }
            }else if (Objects.equals(searchDataInConditionDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_OUTSTOCK.getCode())){
                searchDataInConditionDTO.getConditionsList().addAll(packageWaitOutstockCondition(formDataListDTO));
            }else if (Objects.equals(searchDataInConditionDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode())){
                searchDataInConditionDTO.getConditionsList().addAll(packageWaitInstockCondition(formDataListDTO));
            }else if (Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())
                    || Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.WAREHOUSE.getCode())
                    || Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.SERVICE_PROJECT.getCode())
                    || Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.STOCK_FLOW_BILL.getCode())
                    || Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.BATCH_FLOW_BILL.getCode())
                    || Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.STOCK_STANDING_BOOK.getCode())){
                // 产品筛选仓库时需要用仓库的业务类型去组装条件
                Integer businessType = searchDataInConditionDTO.getBusinessType();
                if (Objects.equals(searchDataInConditionDTO.getAttr(), ProductEnum.WAREHOUSE.getAttr())) {
                    businessType = XbbRefTypeEnum.WAREHOUSE.getCode();
                }
                if(!Objects.equals(1,forChart) && !Objects.equals(1,forScore)) {
                    saasListDataPermissionHelp.listDepAndUserDataPermission(searchDataInConditionDTO.getShouldConditionsList(), searchDataInConditionDTO.getLoginUser(), businessType, searchDataInConditionDTO.getLoginUser().getDepSet());
                }
                if (Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())  && Objects.equals(searchDataInConditionDTO.getSubBusinessType(),XbbRefTypeEnum.PRODUCT.getCode()) && Objects.isNull(searchDataInConditionDTO.getStatusFilter())){
                    // 25678 新建合同筛选产品还是可以看到，不能选择。（客户觉得下架了应该看不到）产品列表页下架产品筛选也是这，需要区分开
                    //与产品列表的唯一区别，没有subBusinessType
                    List<ConditionsEntityExt> conditionsList = searchDataInConditionDTO.getConditionsList();
                    ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(ProductEnum.ONLINE.getAttr());
                    conditionsEntityExt.setValue(Arrays.asList(1,2));
                    conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
                    conditionsEntityExt.setFieldType(ProductEnum.ONLINE.getFieldType());
                    conditionsList.add(conditionsEntityExt);
                }
            }else {
                if(!Objects.equals(1,forChart) && !Objects.equals(1,forScore)) {
                    List<ConditionsEntityExt> permission = saasListDataPermissionHelp.listDataPermission(false, searchDataInConditionDTO.getConditionsList(), searchDataInConditionDTO.getLoginUser(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSubBusinessType());
                    // 共享权限处理
                    ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permission, Collections.singletonList(searchDataInConditionDTO.getFormId()), searchDataInConditionDTO.getLoginUser());
                    searchDataInConditionDTO.setSharePermission(sharePermission);
                }
            }
        } else {
            if(!Objects.equals(1,forChart) && !Objects.equals(1,forScore)) {
                List<ConditionsEntityExt> condition = formDataListSearchHelp.getPaasPermission(formDataListDTO);
                // 共享权限处理
                ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(condition, Collections.singletonList(searchDataInConditionDTO.getFormId()), searchDataInConditionDTO.getLoginUser());
                    searchDataInConditionDTO.setSharePermission(sharePermission);
                searchDataInConditionDTO.setSharePermission(sharePermission);
            }
        }

        Integer del = packageDelCondition(searchDataInConditionDTO.getSubBusinessType());
        del = del == 0 ? Objects.equals(searchDataInConditionDTO.getDel(),1) ? 1 : del : del;
        searchDataInConditionDTO.setDel(del);
    }

    public void packageWaitPurchasePurchaseCondition(FormDataListDTO formDataListDTO) throws XbbException {
        String corpid = formDataListDTO.getCorpid();
        List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>();
        List<ConditionsEntityExt> conditions = formDataListDTO.getConditions();
        if (CollectionsUtil.isNotEmpty(conditions)){
            Iterator<ConditionsEntityExt> iterator = conditions.iterator();
            while (iterator.hasNext()){

                ConditionsEntityExt next = iterator.next();
                String attr = next.getAttr();
                List<Object> value = next.getValue();
                if(Objects.equals(attr, "array_2")){
                    if (CollectionsUtil.isNotEmpty(value)){
                        // 直接塞入合同ID
                        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                        conditionsEntityExt.setAttr(ContractProductSubFormEnum.CONTRACT_ID.getDataAttr());
                        conditionsEntityExt.setFieldType(FieldTypeEnum.DATAID.getType());
                        conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
                        conditionsEntityExt.setValue(value);
                        // 因为这些字段在合同产品的es数据中都在data字段里面 所以都先设置为text
                        conditionsEntityExt.setFieldType(FieldTypeEnum.SEPARATOR.getType());
                        conditionsEntityExtList.add(conditionsEntityExt);
                        iterator.remove();
                    }
                }else if (Objects.equals(TransferEnum.PRODUCTS.getAttr(),attr)){
                    ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(ContractProductSubFormEnum.PRODUCT_ID.getDataAttr());
                    conditionsEntityExt.setFieldType(FieldTypeEnum.DATAID.getType());
                    conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
                    conditionsEntityExt.setFieldType(FieldTypeEnum.SEPARATOR.getType());
                    conditionsEntityExt.setValue(value);
                    conditionsEntityExtList.add(conditionsEntityExt);
                    iterator.remove();
                }
            }
        }
        formDataListDTO.getConditions().addAll(conditionsEntityExtList);
    }

    /**
     * 封装待采购条件
     * @param formDataListDTO
     * @return
     * @throws XbbException
     */
    public List<ConditionsEntityExt> packageWaitPurchaseCondition(FormDataListDTO formDataListDTO) throws XbbException {
        if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
            for (ConditionsEntityExt conditionsEntityExt : formDataListDTO.getConditions()) {
                if (Objects.equals(conditionsEntityExt.getAttr(), ProductEnum.SPECIFICATION.getAttr())) {
                    conditionsEntityExt.setAttr(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
                    break;
                }
            }
        }
        //获取所有的缺货合同
        List<ContractProductEntity> allContractProductList = contractProductModel.getAllContractProduct(formDataListDTO.getCorpid(),ContractProduceEnum.WAIT_PURCHASE.getCode());
        //每个缺货产品对应的缺货合同订单列表
        Set<Long> dataIdSet = new HashSet<>();
        Set<Long> contractIdSet = new HashSet<>();
        allContractProductList.forEach(entity-> contractIdSet.add(entity.getContractId()));
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termsQuery(StringConstant.DATA_ID, contractIdSet));
        boolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ARCHIVED), ArchivedEnum.ARCHIVED.getCode()));
        boolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ALL_OUT_BOUND), AllOutBoundEnum.ALL_OUT.getCode()));
        List<ContractEntityExt> contractList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTRACT, boolQueryBuilder, ContractEntityExt.class, Collections.singletonList(StringConstant.SAAS_LINK_BUSINESS_ID));
        List<Long> needShowContractIdList = new ArrayList<>();
        contractList.forEach(entity-> needShowContractIdList.add(entity.getId()));
        List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
            for (ContractProductEntity entity : allContractProductList){
                //产品分组，拿产品id
                if (needShowContractIdList.contains(entity.getContractId())) {
                    dataIdSet.add(entity.getProductId());
                }
            }
            List<List<ConditionsEntityExt>> shouldConditionList = new ArrayList<>();
//            saasListDataPermissionHelp.listDepAndUserDataPermission(shouldConditionList,userEntity,XbbRefTypeEnum.PRODUCT.getCode(), formDataListDTO.getLoginUser().getDepSet());
            formDataListDTO.setShouldConditions(shouldConditionList);
        } else {
            List<PaasFormEntityExt> paasFormEntityExtList = paasFormService.getEnableContractFormList(formDataListDTO.getLoginUser());
            List<Long> formIdList = new ArrayList<>();
            List<Long> contractIdList = new ArrayList<>();
            List<Long> orderIdList = new ArrayList<>();
            for (PaasFormEntityExt entityExt : paasFormEntityExtList){
                formIdList.add(entityExt.getId());
                if (Objects.equals(entityExt.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                    orderIdList.add(entityExt.getId());
                } else {
                    contractIdList.add(entityExt.getId());
                }
            }
            if (formIdList.isEmpty()){
                formIdList.add(-1L);
            }
            formDataListDTO.setFormIdList(formIdList);
            formDataListDTO.setLimitForms(true);
            dataIdSet = contractIdSet;
            // 合同不用判断状态，订单需要加状态判断
            if (!orderIdList.isEmpty()) {
                if (contractIdList.isEmpty()){
                    contractIdList.add(-1L);
                }
                List<List<ConditionsEntityExt>> shouldConditionList = new ArrayList<>();
                shouldConditionList.add(Collections.singletonList(new ConditionsEntityExt("formId", "", FieldTypeEnum.FORM_ID.getType(), ConditionEnum.IN.getSymbol(), new ArrayList<>(contractIdList))));
                shouldConditionList.add(Arrays.asList(new ConditionsEntityExt("formId", "", FieldTypeEnum.FORM_ID.getType(), ConditionEnum.IN.getSymbol(), new ArrayList<>(orderIdList)), new ConditionsEntityExt(OrderEnum.STATUS.getAttr(), "", OrderEnum.STATUS.getFieldType(), ConditionEnum.NOIN.getSymbol(), Arrays.asList(OrderStatusEnum.PENDING_ORDER_REVIEW.getCode(),OrderStatusEnum.PENDING_FINANCIAL_REVIEW.getCode(),OrderStatusEnum.ABOLISHED.getCode()))));
                formDataListDTO.setShouldConditions(shouldConditionList);
            }
//            saasListDataPermissionHelp.listDataPermission(conditionsEntityExtList,userEntity,XbbRefTypeEnum.CONTRACT.getCode(), XbbRefTypeEnum.CONTRACT.getCode());
        }
        //根据合同id获取分页后的合同列表
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setAttr(FieldTypeEnum.DATAID.getAlias());
        conditionsEntityExt.setFieldType(FieldTypeEnum.DATAID.getType());
        conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
        dataIdSet.add(-1L);
        conditionsEntityExt.setValue(new ArrayList<>(dataIdSet));
        if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.CONTRACT.getCode())){
            conditionsEntityExtList.add(new ConditionsEntityExt(ContractEnum.ARCHIVED.getAttr(),"",ContractEnum.ARCHIVED.getFieldType(),ConditionEnum.EQUAL.getSymbol(),Collections.singletonList(ArchivedEnum.UN_ARCHIVED.getCode())));
            conditionsEntityExtList.add(new ConditionsEntityExt(ContractEnum.ALL_OUT_BOUND.getAttr(),"",ContractEnum.ALL_OUT_BOUND.getFieldType(),ConditionEnum.EQUAL.getSymbol(),Collections.singletonList(AllOutBoundEnum.NON_OUT.getCode())));
            conditionsEntityExtList.add(new ConditionsEntityExt(ContractEnum.SHIP_STATUS.getAttr(),"",ContractEnum.SHIP_STATUS.getFieldType(),ConditionEnum.NOEQUAL.getSymbol(),Collections.singletonList(ShipStatusEnum.CLOSED.getCode())));
        }
        conditionsEntityExtList.add(conditionsEntityExt);
        return conditionsEntityExtList;
    }

    /**
     * @Author: wujian
     * @Description: 待采购合同视图列表页数据封装
     * @Date: 下午2:10 2021/9/7
     * @Param:
     * @return: void
     **/
    public PaasFormDataEsListVO packageWaitPurchase(FormDataListDTO formDataListDTO) throws XbbException {
        Integer pageSize = formDataListDTO.getPageSize();
        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        String corpid = formDataListDTO.getCorpid();
        Integer subBusinessType = formDataListDTO.getSubBusinessType();

        // 应产品要求 解释按照原来的逻辑 用第一个合同的为准
        // 根据corpid以及businesstype拿出第一个合同解释 用来设置表头是否展示 数据是否隐藏
        PaasFormExplainEntity paasFormExplainEntity;
        Map<String, Object> paasFormParam = new HashMap<>();
        paasFormParam.put("corpid", corpid);
        paasFormParam.put("enable", 1);
        paasFormParam.put("del", 0);
        paasFormParam.put("distributorMark", DistributorMarkEnum.OTHER.getCode());
        paasFormParam.put("businessType", XbbRefTypeEnum.CONTRACT.getCode());
        paasFormParam.put("orderByStr", "sort ASC ");
        List<PaasFormEntity> paasFormEntityList = paasFormModel.findEntity(paasFormParam);
        if (CollectionsUtil.isNotEmpty(paasFormEntityList)){
            Long formId = paasFormEntityList.get(0).getId();
            paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        }else {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "表单解释查询出错");
        }


        // 符合条件的缺货合同ID集合
        List<Long> contractIdList = new ArrayList<>();
        Long updateTime = formDataListDTO.getLastUpdateTime();
        Integer listSize = formDataListDTO.getPageSize();
        Integer onPage = formDataListDTO.getOnPage();


        LinkedHashMap<Long, List<WaitContractProductPojo>> newWaitContractProductPojoMap = new LinkedHashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> cidList = new ArrayList<>();
        newWaitContractProductPojoMap = getNewWaitContractProductPojoMap(newWaitContractProductPojoMap,formDataListDTO,corpid , cidList);
        // 返回是否最后一页标识
        formDataListVO.setIsLast(formDataListDTO.getIsLast());
        // 如果是点击了上一页 那么下一页必定能点击
        if (Objects.nonNull(onPage) && Objects.equals(onPage,1)){
            formDataListVO.setIsLast(0);
        }
        formDataListVO.setIsFirst(0);
        if (Objects.isNull(updateTime) && newWaitContractProductPojoMap.size() < listSize){
            formDataListVO.setIsFirst(1);
        }
        // 如果是点击上一页 就将是否是最后一页赋值给isFirst 适用于只有两页数据场景
        if (Objects.nonNull(onPage) && Objects.equals(onPage,1)){
//            formDataListDTO.setis
        }
        if (Objects.nonNull(paasFormExplainEntity)){
            formDataListDTO.setFormId(paasFormExplainEntity.getFormId());
            // 根据解释过滤字段
            HandleExplainPojo handleExplainPojo = formDataListSearchHelp.handleExplain(formDataListDTO);
            formDataListVO.setForm(handleExplainPojo.getForm());
            List<FieldAttrEntity> explainList = handleExplainPojo.getExplainList();
            ListOptionPackagePojo listOptionPackagePojo = setOptionBase(contractIdList,formDataListDTO, new PaasFormDataEsListVO(),null);
            // 拿到表头需要的6个字段
            handelSaasSpecialList(explainList,XbbRefTypeEnum.CONTRACT.getCode(),XbbRefTypeEnum.WAIT_PURCHASE.getCode());
            // 将移动端负责人字段添家到可见字段里面 减少移动端再次查询解释过滤
            List<FieldAttrEntity> canSeeExplainList = new ArrayList<>();
            canSeeExplainList.addAll(explainList);
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMapByAttr(paasFormExplainEntity.getExplains(), ContractEnum.OWNER_ID.getAttr());
            canSeeExplainList.add(explainMap.getOrDefault(ContractEnum.OWNER_ID.getAttr(),new FieldAttrEntity()));
            FieldAttrEntity optionAttrOption = new FieldAttrEntity();
            optionAttrOption.setAttr(ListOptionEnum.OPTION.getAttr());
            optionAttrOption.setAttrName(ListOptionEnum.OPTION.getAttrName());
            optionAttrOption.setFieldType(FieldTypeEnum.OPTION.getType());
            optionAttrOption.setSort(1);
            explainList.add(optionAttrOption);
            // 缺货产品表头
            FieldAttrEntity fieldAttrEntity = new FieldAttrEntity();
            fieldAttrEntity.setAttr(ListOptionEnum.WAIT_PURCHASE_CONTRACT.getAttr());
            fieldAttrEntity.setAttrName(ListOptionEnum.WAIT_PURCHASE_CONTRACT.getAttrName());
            fieldAttrEntity.setFieldType(FieldTypeEnum.CONTRACT.getType());
            fieldAttrEntity.setSaasAttr("wait_purchase");
            fieldAttrEntity.setLinkedType(XbbRefTypeEnum.PURCHASE.getCode());
            fieldAttrEntity.setVisible(1);
            fieldAttrEntity.setIsOpen(1);
            fieldAttrEntity.setNoEditable(0);
            explainList.add(fieldAttrEntity);
            explainList.forEach(item -> item.setDisableListSort(1));
            formDataListVO.setHeadList(explainList);
            if (!newWaitContractProductPojoMap.isEmpty()){
                contractIdList.addAll(newWaitContractProductPojoMap.keySet());
            }else {
                formDataListVO.setPaasFormDataESList(new ArrayList<>());
                /* ==================== 上部按钮权限和下部按钮权限 ==================== */
                formDataListSearchHelp.setButtons(formDataListDTO, formDataListVO);
                return formDataListVO;
            }
            contractIdList.add(-1L);
            // 根据合同id查询所有合同数据封装列表数据
            Map<String,Object> param = new HashMap<>();
            param.put("corpid",corpid);
            param.put("del",0);
            param.put("idIn",contractIdList);
            param.put("orderByStr","update_time DESC");
            List<ContractEntityExt> contractEntityExtList =contractModel.findEntitys(param);
            List<PaasFormDataEntityExt>  paasFormDataESList = new ArrayList<>();
            List<String> creatIdList = new ArrayList<>();
            Map<String,String> userNameMap = new HashMap<>();
            if (CollectionsUtil.isNotEmpty(contractEntityExtList)){
                contractEntityExtList.forEach(item -> creatIdList.add(item.getCreatorId()));
                if (CollectionsUtil.isNotEmpty(creatIdList)){
                    List<UserEntity> userList = userModel.getByUserIdIn(corpid, creatIdList);
                    if (CollectionsUtil.isNotEmpty(userList)){
                        userList.forEach(item ->userNameMap.put(item.getUserId(),item.getName()));
                    }
                }
            }
            // 查询出团队数据
            Map<String,Object> contractUserparam = new HashMap<>();
            contractUserparam.put("corpid",corpid);
            contractUserparam.put("del",0);
            contractUserparam.put("contractIdIn",contractIdList);
            List<ContractUserEntity> contractUserEntityList = contractUserModel.findEntitys(contractUserparam);
            // 负责人Map
            Map<Long,List<String>> ownerMap = new HashMap<>();
            // 协同人Map
            Map<Long,List<String>> coUserMap = new HashMap<>();
            // 封装合同数据的负责人协同人数据
            if (CollectionsUtil.isNotEmpty(contractUserEntityList)){
                for (ContractUserEntity contractUserEntity : contractUserEntityList) {
                    Integer isMain = contractUserEntity.getIsMain();
                    Long contractId = contractUserEntity.getDataId();
                    String userId = contractUserEntity.getUserId();
                    if (Objects.equals(isMain,1)){
                        if (ownerMap.containsKey(contractId)){
                            List<String> list = ownerMap.get(contractId);
                            list.add(userId);
                            ownerMap.put(contractId,list);
                        }else{
                            List<String> owenList = new ArrayList<>();
                            owenList.add(userId);
                            ownerMap.put(contractId,owenList);
                        }

                    }else {
                        if (coUserMap.containsKey(contractId)){
                            List<String> list = coUserMap.get(contractId);
                            list.add(userId);
                            coUserMap.put(contractId,list);
                        }else{
                            List<String> coList = new ArrayList<>();
                            coList.add(userId);
                            coUserMap.put(contractId,coList);
                        }
                    }
                }
            }

            for (ContractEntityExt contractEntityExt : contractEntityExtList) {
                JSONObject data = contractEntityExt.getData();
                PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
                Long contractId = contractEntityExt.getId();
                List<WaitContractProductPojo> waitContractProductPojos = newWaitContractProductPojoMap.get(contractId);
                // 封装待采购产品数量
                if (CollectionsUtil.isNotEmpty(waitContractProductPojos)){
                    JSONObject json = new JSONObject();
                    Double num = 0D;
                    for (WaitContractProductPojo waitContractProductPojo : waitContractProductPojos) {
                        num += waitContractProductPojo.getProductNum();
                    }
                    ProductFieldPojo stockField = saasFormHelp.getProductFieldPojo(RedisPrefixConstant.PRODUCT_STOCK,ProductEnum.STOCK.getAttr(), corpid);
                    Integer accuracy = stockField.getAccuracy();
                    num = attrDecimalPrecisionHelper.setPrecision(num, accuracy);
                    json.put("previewText", String.format(I18nMessageUtil.getMessage(SaasConstant.WAIT_OUT_OF_STOCK_PRODUCTS), waitContractProductPojos.size(), num.toString()));
                    data.put(ListOptionEnum.WAIT_PURCHASE_CONTRACT.getAttr(),json);
                }
                data.put(ContractEnum.CONTRACT_NO.getAttr(),contractEntityExt.getSerialNo());
                JSONArray customerArray = new JSONArray();
                JSONObject customer = new JSONObject();
                Object customerId = data.get(ContractEnum.LINK_CUSTOMER.getAttr());
                String name = data.getString(ContractEnum.LINK_CUSTOMER_HIDE.getAttr());
                customer.put("id",customerId);
                customer.put("name",name);
                customer.put("businessType",XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                customer.put("saasMark",1);
                customerArray.add(customer);
                data.put(ContractEnum.LINK_CUSTOMER.getAttr(),customerArray);
                String userName = userNameMap.get(contractEntityExt.getCreatorId()) == null ? "" : userNameMap.get(contractEntityExt.getCreatorId());
                data.put(ContractEnum.CREATOR_ID.getAttr(),userName);
                data.put(ContractEnum.ADD_TIME.getAttr(),contractEntityExt.getAddTime());
                data.put(ContractEnum.UPDATE_TIME.getAttr(),contractEntityExt.getUpdateTime());
                // 塞入一键采购按钮
                List<ButtonPojo> optionList = new ArrayList<>();
                optionList.add(new ButtonPojo(ListOptionTabEnum.PURCHASE, XbbRefTypeEnum.PURCHASE.getCode()));
                JSONObject option = new JSONObject();
                option.put("value", optionList);
                data.put(ListOptionEnum.OPTION.getAttr(), option);
                // 用于移动端可见不可见标记
                data.put(ContractEnum.OWNER_ID.getAttr(),"canSeeTag");
                paasFormDataEntityExt.setData(data);
                paasFormDataEntityExt.setDataId(contractId);
                paasFormDataEntityExt.setCreatorId(contractEntityExt.getCreatorId());
                paasFormDataESList.add(paasFormDataEntityExt);
            }


            // 处理列表页字段排序
            formDataListSearchHelp.explainFieldSort(formDataListDTO, formDataListVO);
            //表单冻结和隐藏列设置（在按钮设置后处理，防止操作列无法冻结和隐藏）
            formDataListSearchHelp.setFixedAndInvisible(formDataListDTO, formDataListVO);
            PageHelper pageHelper = new PageHelper();
            pageHelper.setPageSize(pageSize);
            formDataListVO.setPageHelper(pageHelper);
            // 处理列表页数据高级不可见
            parseContractDataCanSee(paasFormDataESList, canSeeExplainList, formDataListDTO.getLoginUser(), ownerMap,coUserMap);
            formDataListVO.setPaasFormDataESList(paasFormDataESList);
            formDataListVO.setFirstupdateTime(formDataListDTO.getFirstTime());
            formDataListVO.setUpdateTime(formDataListDTO.getLastTime());
            /* ==================== 上部按钮权限和下部按钮权限 ==================== */
            formDataListSearchHelp.setButtons(formDataListDTO, formDataListVO);
        }else {
            // TODO 报错提示
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "表单解释查询出错");
        }
        return formDataListVO;
    }

    public void parseContractDataCanSee(List<PaasFormDataEntityExt> paasFormDataESList,List<FieldAttrEntity> headListExplain, UserVO loginUser,Map<Long,List<String>> ownerIdMap,Map<Long,List<String>> coUserIdMap)  throws XbbException {
        if (CollectionsUtil.isNotEmpty(paasFormDataESList)){
            String userId = loginUser.getUserId();
            Map<String, FieldAttrEntity> expalinMap = ExplainUtil.getExplainMapByList(headListExplain);
            ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            userAndDepartmentGetDTO.setLoginUser(loginUser);
            userAndDepartmentGetDTO.setUserId(userId);
            userAndDepartmentGetDTO.setCorpid(loginUser.getCorpid());
            UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
            Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
            Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
            parseSingleRowDataDTO.setExplainMap(expalinMap);
            parseSingleRowDataDTO.setUserMap(userMap);
            parseSingleRowDataDTO.setDepartmentMap(departmentMap);
            parseSingleRowDataDTO.setLoginUser(loginUser);
            parseSingleRowDataDTO.setUserId(userId);
            parseSingleRowDataDTO.setCorpid(loginUser.getCorpid());
            for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
                JSONObject data = paasFormDataEntityExt.getData();
                String creatorId = paasFormDataEntityExt.getCreatorId();
                Long contractId = paasFormDataEntityExt.getDataId();
                List<String> ownerIdList = ownerIdMap.getOrDefault(contractId,new ArrayList<>());
                List<String> coUserId = coUserIdMap.getOrDefault(contractId,new ArrayList<>());
                Map<String, Boolean> canSeeMap = parseCanseeParam(headListExplain, creatorId,ownerIdList,coUserId,parseSingleRowDataDTO);
                for (Map.Entry<String, Boolean> stringBooleanEntry : canSeeMap.entrySet()) {
                    String key = stringBooleanEntry.getKey();
                    Boolean value = stringBooleanEntry.getValue();
                    if (!value ){
                        if (Objects.equals(ContractEnum.CONTRACT_NO.getAttr(),key)){
                            data.put(ContractEnum.CONTRACT_NO.getAttr(),"");
                        }else if (Objects.equals(ContractEnum.NAME.getAttr(),key)){
                            data.put(ContractEnum.NAME.getAttr(),"");
                        }else if (Objects.equals(ContractEnum.LINK_CUSTOMER.getAttr(),key)){
                            data.put(ContractEnum.LINK_CUSTOMER.getAttr(),"");
                        }else if (Objects.equals(ContractEnum.CREATOR_ID.getAttr(),key)){
                            data.put(ContractEnum.CREATOR_ID.getAttr(),"");
                        }else if (Objects.equals(ContractEnum.ADD_TIME.getAttr(),key)){
                            data.put(ContractEnum.ADD_TIME.getAttr(),"");
                        }else if (Objects.equals(ContractEnum.UPDATE_TIME.getAttr(),key)){
                            data.put(ContractEnum.UPDATE_TIME.getAttr(),"");
                        }else if (Objects.equals(ContractEnum.OWNER_ID.getAttr(),key)){
                            data.put(ContractEnum.OWNER_ID.getAttr(),null);
                        }
                    }
                }
            }
        }
    }
    /**
     * @Author: wujian
     * @Description: 查询合同列表页数据封装
     * @Date: 下午3:18 2021/9/8
     * @Param: [formDataListDTO]
     * @return: com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage
     **/
    public XbbAggregatedPage  getWaitPurchaseContract(FormDataListDTO formDataListDTO) throws XbbException {

        boolean isOnPage = false;
        Integer onPage = formDataListDTO.getOnPage();
        if (Objects.nonNull(onPage) && Objects.equals(onPage,1)){
            isOnPage = true;
        }

        Long lastUpdateTime = formDataListDTO.getLastUpdateTime();
        String nameLike = formDataListDTO.getNameLike();

        String corpid = formDataListDTO.getCorpid();
        // 获取所有启用的合同订单模版
        List<PaasFormEntityExt> paasFormEntityExtList = paasFormService.getEnableContractFormList(formDataListDTO.getLoginUser());
        List<Long> contractFormIdList = new ArrayList<>();
        List<Long> orderFormIdList = new ArrayList<>();
        // 拿出所有合同表单ID 以及经销商的fromID 用作下面es做聚合时使用
        if (CollectionsUtil.isNotEmpty(paasFormEntityExtList)){
            for (PaasFormEntityExt entityExt : paasFormEntityExtList){
                if (Objects.equals(entityExt.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                    orderFormIdList.add(entityExt.getId());
                }else {
                    contractFormIdList.add(entityExt.getId());
                }
            }
        }
        // 没有模版启用时
        if (CollectionsUtil.isEmpty(contractFormIdList) && CollectionsUtil.isEmpty(orderFormIdList)){
            throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350007);
        }
        List<SortBuilder> sortBuilders = new ArrayList<>();
        Map<String, String> sortMap = formDataListDTO.getSortMap();
        sortBuilders = Collections.singletonList(new FieldSortBuilder(ContractEnum.UPDATE_TIME.getAttr()).order(SortOrder.DESC));
        // 更新时间倒序排序
        if (Objects.nonNull(lastUpdateTime) && isOnPage && sortMap.isEmpty()){
            sortBuilders = Collections.singletonList(new FieldSortBuilder(ContractEnum.UPDATE_TIME.getAttr()).order(SortOrder.ASC));
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        // 查询合同订单有产品 且出库状态不是全部出库且不是关闭的的 且未归档 更新时间倒序排序 del= 0
        BoolQueryBuilder contractBoolQueryBuilder = boolQuery();
        if (CollectionsUtil.isNotEmpty(contractFormIdList)){
            contractBoolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
            contractBoolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTRACT.getType()));
            contractBoolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
            contractBoolQueryBuilder.filter(termsQuery(ParameterConstant.FORMID,contractFormIdList));
            contractBoolQueryBuilder.filter(existsQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.PRODUCT).replace(".keyword", "")));
            contractBoolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ARCHIVED), ArchivedEnum.ARCHIVED.getCode()));
            contractBoolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ALL_OUT_BOUND), AllOutBoundEnum.ALL_OUT.getCode()));
            contractBoolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.SHIP_STATUS), ShipStatusEnum.CLOSED.getCode()));
            contractBoolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.SHIP_STATUS), ShipStatusEnum.SHIPPED.getCode()));
            if (StringUtil.isNotEmpty(nameLike)){
                contractBoolQueryBuilder.should(matchPhraseQuery("data." + ContractEnum.NAME.getAttr() , nameLike));
                contractBoolQueryBuilder.should(matchPhraseQuery("data." + ContractEnum.NAME.getAttr() + ".keyword", nameLike));
                contractBoolQueryBuilder.should(matchPhraseQuery( ContractEnum.CONTRACT_NO.getAttr() + ".keyword", nameLike));
                contractBoolQueryBuilder.should(matchPhraseQuery( ContractEnum.CONTRACT_NO.getAttr() , nameLike));
                contractBoolQueryBuilder.minimumShouldMatch(1);
            }
            // TODO 创建时间大于上线日期 暂时写为2022-03-10
            contractBoolQueryBuilder.filter(rangeQuery(ParameterConstant.ADD_TIME).gte(BasicConstant.JXC_ONLINE_DATE));
            if (Objects.nonNull(lastUpdateTime) && !isOnPage){
                contractBoolQueryBuilder.filter(rangeQuery(ContractEnum.UPDATE_TIME.getAttr()).lt(lastUpdateTime));
            }else if (Objects.nonNull(lastUpdateTime) && isOnPage){
                contractBoolQueryBuilder.filter(rangeQuery(ContractEnum.UPDATE_TIME.getAttr()).gt(lastUpdateTime));
            }

            boolQueryBuilder.should(contractBoolQueryBuilder);

        }
        // 如果有经销商的订单的 需要过滤订单状态
        if (CollectionsUtil.isNotEmpty(orderFormIdList)){
            List<String> orderStatusList = new ArrayList<>();
            orderStatusList.add(OrderStatusEnum.DELIVERED.getCode());
            orderStatusList.add(OrderStatusEnum.RECEIVED.getCode());
            // 查询订货单有产品 且出库状态不是全部出库且不是关闭的的 且未归档  订单状态未待发货 或者待收货 更新时间倒序排序 del= 0
            BoolQueryBuilder orderBoolQueryBuilder = boolQuery();
            orderBoolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
            orderBoolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTRACT.getType()));
            orderBoolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
            orderBoolQueryBuilder.filter(termsQuery(ParameterConstant.FORMID,orderFormIdList));
            orderBoolQueryBuilder.filter(termQuery(ContractEnum.STATUS.getAttr(),orderStatusList));
            orderBoolQueryBuilder.filter(existsQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.PRODUCT).replace(".keyword", "")));
            orderBoolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ARCHIVED), ArchivedEnum.ARCHIVED.getCode()));
            orderBoolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ALL_OUT_BOUND), AllOutBoundEnum.ALL_OUT.getCode()));

            if (StringUtil.isNotEmpty(nameLike)){
                orderBoolQueryBuilder.should(matchPhraseQuery(ContractEnum.CONTRACT_NO.getAttr(), nameLike));
                orderBoolQueryBuilder.should(matchPhraseQuery(ContractEnum.CONTRACT_NO.getAttr() + ".keyword", nameLike));
                orderBoolQueryBuilder.minimumShouldMatch(1);
            }
            // TODO 创建时间大于等于上线日期 暂时写为2022-03-10
            orderBoolQueryBuilder.filter(rangeQuery(ParameterConstant.ADD_TIME).gte(BasicConstant.JXC_ONLINE_DATE));
            // 如果传入了最后一个更新时间 则要小于上次的最后一个更新时间
            if (Objects.nonNull(lastUpdateTime) && !isOnPage){
                orderBoolQueryBuilder.filter(rangeQuery("updateTime").lt(lastUpdateTime));
            }else if (Objects.nonNull(lastUpdateTime) && isOnPage){
                contractBoolQueryBuilder.filter(rangeQuery("updateTime").gt(lastUpdateTime));
            }
            boolQueryBuilder.should(orderBoolQueryBuilder);
        }
        boolQueryBuilder.minimumShouldMatch(1);
        // 数据权限过滤
//        UserEntity userEntity = new UserEntity();
//        UserVO userVO = formDataListDTO.getLoginUser();
//        BeanUtil.copyProperties(userVO, userEntity);
//        Integer dataPermission = userModel.getDataPermission(userEntity);
//        List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, userVO.getUserId(), userVO.getCorpid(), BasicConstant.ZERO,false);
//        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
//        conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
//        conditionsEntityExt.setValue(new ArrayList<>(userIdIn));
//        conditionsEntityExt.setAttr(FieldTypeEnum.TEAM_USER.getAlias());
//        conditionsEntityExt.setFieldType(FieldTypeEnum.TEAM_USER.getType());
//        formDataListDTO.getConditions().add(conditionsEntityExt);
        if (Objects.nonNull(formDataListDTO.getConditions())){
            List<ConditionsEntityExt> conditions = formDataListDTO.getConditions();
            Iterator<ConditionsEntityExt> iterator = conditions.iterator();
            while (iterator.hasNext()){
                ConditionsEntityExt conditionsEntity = iterator.next();
                if(Objects.equals(conditionsEntity.getAttr(), "array_2")){

                    List<Object> idList = conditionsEntity.getValue();
                    if (CollectionsUtil.isNotEmpty(idList)){
                        boolQueryBuilder.filter(termsQuery(ParameterConstant.ID,idList));
                    }
                    iterator.remove();
                }
            }
            if (Objects.nonNull(formDataListDTO.getConditions())){
                EsUtil.parseCondition(boolQueryBuilder,formDataListDTO.getConditions(),"",corpid,XbbRefTypeEnum.WAIT_PURCHASE.getCode());
            }
        }
        XbbAggregatedPage aggregatedPage;
        try {
            aggregatedPage = esHelper.findByPage(IndexTypeEnum.IDX_SAAS_CONTRACT, boolQueryBuilder, PaasFormDataEntityExt.class, null,formDataListDTO.getPage(),formDataListDTO.getSearchPageSize(),sortBuilders);
        } catch (Exception e) {
            aggregatedPage = null;
            Log.info("待采购列表es数据查询失败");
        }
        return aggregatedPage;
    }

    /**
     * @Author: wujian
     * @Description: 待采购合同+产品维度视图
     * @Date: 下午1:58 2021/10/14
     * @Param: [formDataListDTO]
     * @return: com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO
     **/
    public PaasFormDataEsListVO packageWaitPurchaseProduct(FormDataListDTO formDataListDTO) throws XbbException{
        Boolean isDingtalk = false ;
        String platform = formDataListDTO.getPlatform();
        if (Objects.equals(PlatFormEnum.DINGTALK.getValue(),platform)){
            isDingtalk = true;
        }
        long time = DateTimeUtil.getDate().getTime();
        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        String corpid = formDataListDTO.getCorpid();
        boolean isEnglish = false;
        String locale = formDataListDTO.getLocale();
        if (Objects.equals(locale,"en_US")){
            isEnglish = true;
        }
        List<FieldAttrEntity> headList = new ArrayList<>();
        // 获取需要处理可见的表头 以及表头解释
        Map<String, List<FieldAttrEntity>> needCanSeeExplainMap = handleWaitPurchaseProductHead(corpid, headList);
        handleHeadList(headList,isEnglish);
        formDataListVO.setHeadList(headList);
        //表单获取
        PaasFormEntityExt form = formDataListSearchHelp.getForm(formDataListDTO);
        formDataListVO.setForm(form);
        /* ==================== 上部按钮权限和下部按钮权限 ==================== */
        formDataListSearchHelp.setButtons(formDataListDTO, formDataListVO);

        List<Long> contractIdList = new ArrayList<>();
        Map<Long,ContractEntityExt> contractEntityExtMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,ProductEntityExt> productEntityExtMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<PaasFormDataEntityExt>  paasFormDataESList = new ArrayList<>();
        List<Long> productIdList = new ArrayList<>();
        Set<Long> productIdSet = new HashSet<>();
        List<Long> parentIdList = new ArrayList<>();
        List<String> onlyKeyList = new ArrayList<>();
        // 查询出符合条件的合同产品
        List<ContractProductEntity> waitPurchaseProductEntitys = contractProductService.findWaitPurchaseProductEntitys(formDataListDTO);
        Integer count = contractProductService.findWaitPurchaseProductCount(formDataListDTO);
        formDataListVO.setPageHelper(new PageHelper(formDataListDTO.getPage(), formDataListDTO.getPageSize()).setRowsCount(count));
        if(CollectionsUtil.isNotEmpty(waitPurchaseProductEntitys)) {
            waitPurchaseProductEntitys.forEach(item -> {
                contractIdList.add(item.getContractId());
                productIdList.add(item.getProductId());
                productIdSet.add(item.getProductId());
                parentIdList.add(item.getParentId());
                onlyKeyList.add(item.getId() + "_" + item.getProductId());
            });
            // 获取所有合同产品的合同数据
            List<ContractEntityExt> contractEntityExtList = contractModel.findEntitysByIdIn(corpid, 0, contractIdList);

            if (CollectionsUtil.isNotEmpty(contractEntityExtList)) {
                contractEntityExtList.forEach(item -> contractEntityExtMap.put(item.getId(), item));
            }
            // 获取封装用到的所有产品数据
            List<ProductEntityExt> productList = productModel.getProductListByIdIn(corpid, productIdList, DelEnum.NORMAL.getDel());
            if (CollectionsUtil.isNotEmpty(productList)) {
                productList.forEach(item -> productEntityExtMap.put(item.getId(), item));
            }
            // 获取用户容器 方便下面封装
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(formDataListDTO, userAndDepartmentGetDTO);
            Map<String, UserEntity> userMap = userHelp.getUserMap(userAndDepartmentGetDTO);
            //供应商 规格数据查询
            Map<Long, List<SupplierProductEntity>> supplierProductByParentIdIn = supplierProductModel.getSupplierProductByParentIdIn(corpid, productIdList, false);
            Map<Long, List<SpecificationEntity>> specificationMap = specificationModel.getSpecificationMap(corpid, parentIdList);
            // 多单位处理
            Map<String, String> unitItemMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<UnitItemPoJo>> groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
            Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
            List<ItemPoJo> productItems = relativeProductHelp.getBusinessUnitItems(corpid);
            productItems.forEach(item -> {
                if (!Objects.equals(item.getIsOther(), 1)) {
                    unitItemMap.put(item.getValue().toString(), item.getText());
                }
            });
            // key= contractid+productId value = 采购总量
            Map<String, Double> purchaseByContractMap = getPurchaseByContract(corpid, contractIdList);
            List<WaitPurchasePojo> purchaseSupplierByContract = getPurchaseSupplierByContract(corpid, contractIdList);
            // key= contractProductId+productId value = 采购入库总量
            Map<String, Double> purchaseInstockMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (CollectionsUtil.isNotEmpty(purchaseSupplierByContract)) {
                purchaseSupplierByContract.forEach(item -> purchaseInstockMap.put(item.getOnlyKey(), item.getPurchaseInstockNum()));
            }

            // 获取采购结存表所有数据
            List<PurchaseBalanceEntity> purchaseBalanceEntityList = new ArrayList<>();
            if (CollectionsUtil.isNotEmpty(onlyKeyList)) {
                purchaseBalanceEntityList = purchaseBalanceModel.findByOnlyKeys(corpid, onlyKeyList);
            }
            // 超发库存map key = contractid_productid  value=超发库存总量
            Map<String, Double> exceedStockMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (CollectionsUtil.isNotEmpty(purchaseBalanceEntityList)) {
                purchaseBalanceEntityList.forEach(item -> exceedStockMap.put(item.getOnlyKey(), item.getExceedStockNum()));
            }
            int accuary = 6;
            Map<Long, ContractProductEntity> conpdtEntMap = new HashMap<>();
            waitPurchaseProductEntitys.forEach(item -> conpdtEntMap.put(item.getId(), item));
            Map<Long, ProductEntityExt> productMap1 = getProductMap(productIdSet, corpid);
            for (ContractProductEntity waitPurchaseProductEntity : waitPurchaseProductEntitys) {
                if (Objects.nonNull(waitPurchaseProductEntity)) {
                    Long productId = waitPurchaseProductEntity.getProductId();
                    Long contractId = waitPurchaseProductEntity.getContractId();
                    String onlyKey = waitPurchaseProductEntity.getId() + "_" + productId;
                    JSONObject contractProductData = waitPurchaseProductEntity.getData();

                    // 拿到合同数据及产品数据
                    ContractEntityExt contractEntityExt = contractEntityExtMap.get(contractId);


                    ProductEntityExt productEntityExt = productEntityExtMap.get(productId);
                    if (Objects.nonNull(contractEntityExt) && Objects.nonNull(productEntityExt)) {
                        JSONObject contractData = contractEntityExt.getData();
                        JSONObject productData = productEntityExt.getData();
                        JSONObject data = new JSONObject();
                        Double rate = 1D;
                        // TODO 解释冲突处理
                        // data塞入产品数据
                        //data.put(ProductEnum.PRODUCT_IMGS.getAttr(), productData.get(ProductEnum.PRODUCT_IMGS.getAttr()));
                        //处理图片
                        JSONArray thumbnail = new JSONArray();
                        ProductEntityExt productEntity = productMap1.get(productId);
                        if (productEntity != null) {
                            JSONArray productImgs = new JSONArray();
                            JSONObject dataProduct = productEntity.getData();
                            if (Objects.nonNull(dataProduct) && CollectionsUtil.isEmpty(dataProduct.getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr()))) {
                                dataProduct.put(ProductEnum.PRODUCT_IMGS.getAttr(), dataProduct.getJSONArray(ProductEnum.THUMBNAIL.getAttr()));
                            }
                            productImgs = productEntity.getData().getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr());
                            if (productImgs != null && !productImgs.isEmpty()) {
                                thumbnail.add(productImgs.getString(0));
                            }
                        }
                        data.put(ProductEnum.PRODUCT_IMGS.getAttr(), thumbnail);
                        JSONArray productNameArray = new JSONArray();
                        JSONObject productName = new JSONObject();
                        productName.put("name", productData.get(ProductEnum.NAME.getAttr()));
                        productName.put("id", productEntityExt.getData().get(ProductEnum.PARENT_ID.getAttr()));
                        productName.put("businessType", XbbRefTypeEnum.PRODUCT.getCode());
                        productName.put("saasMark", SaasMarkEnum.SAAS.getCode());
                        productNameArray.add(productName);
                        data.put("productName", productNameArray);
                        JSONArray productNoArray = new JSONArray();
                        JSONObject productNo = new JSONObject();
                        productNo.put("name", productEntityExt.getSerialNo());
                        productNo.put("id", productEntityExt.getData().get(ProductEnum.PARENT_ID.getAttr()));
                        productNo.put("businessType", XbbRefTypeEnum.PRODUCT.getCode());
                        productNo.put("saasMark", SaasMarkEnum.SAAS.getCode());
                        productNoArray.add(productNo);
                        data.put("productSerialNo", productNoArray);
                        // 规格解析
                        String specStr = specificationModel.joinSpecification(productData.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()));
                        data.put(ProductEnum.SPECIFICATION.getAttr(), specStr);
                        // 供应商解析
                        JSONArray supplierArr = new JSONArray();
                        Map<Long, String> supplierNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        if (!supplierProductByParentIdIn.isEmpty() && supplierProductByParentIdIn.containsKey(productId)) {
                            List<SupplierProductEntity> supplierProductList = supplierProductByParentIdIn.get(productId);
                            for (SupplierProductEntity supplierProductEntity : supplierProductList) {
                                supplierNameMap.put(supplierProductEntity.getSupplierId(), supplierProductEntity.getSupplierName());
                            }
                            for (Map.Entry<Long, String> entry : supplierNameMap.entrySet()) {
                                JSONObject supplierObj = new JSONObject();
                                supplierObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, entry.getKey());
                                supplierObj.put(StringConstant.BUSINESS_TYPE,XbbRefTypeEnum.SUPPLIER.getCode());
                                supplierObj.put("subBusinessType",XbbRefTypeEnum.SUPPLIER.getCode());
                                supplierObj.put("saasMark",1);
                                supplierObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, entry.getValue());
                                supplierArr.add(supplierObj);
                            }
                        }
                        data.put(ProductEnum.SUPPLIER.getAttr(), supplierArr);
                        // data塞入合同数据
                        JSONArray contractNoArray = new JSONArray();
                        JSONObject contractNo = new JSONObject();
                        contractNo.put("name", contractEntityExt.getSerialNo());
                        contractNo.put("id", contractEntityExt.getDataId());
                        contractNo.put("businessType", XbbRefTypeEnum.CONTRACT.getCode());
                        contractNo.put("saasMark", SaasMarkEnum.SAAS.getCode());
                        contractNoArray.add(contractNo);
                        data.put(ContractEnum.CONTRACT_NO.getAttr(), contractEntityExt.getSerialNo());
                        JSONArray contractNameArray = new JSONArray();
                        JSONObject contractName = new JSONObject();
                        contractName.put("name", contractData.get(ContractEnum.NAME.getAttr()));
                        contractName.put("id", contractEntityExt.getDataId());
                        contractName.put("businessType", XbbRefTypeEnum.CONTRACT.getCode());
                        contractName.put("saasMark", SaasMarkEnum.SAAS.getCode());
                        contractNameArray.add(contractName);
                        data.put(ContractEnum.CONTRACT_NO.getAttr(), contractNoArray);
                        data.put(ContractEnum.NAME.getAttr(), contractNameArray);
                        JSONArray customerArray = new JSONArray();
                        JSONObject customer = new JSONObject();
                        customer.put("name", contractData.get(ContractEnum.LINK_CUSTOMER_HIDE.getAttr()));
                        customer.put("id", contractData.get(ContractEnum.LINK_CUSTOMER.getAttr()));
                        customer.put("businessType", XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                        customer.put("saasMark", SaasMarkEnum.SAAS.getCode());
                        customerArray.add(customer);
                        data.put(ContractEnum.LINK_CUSTOMER.getAttr(), customerArray);
                        String creatName = "";
                        if (!userMap.isEmpty() && Objects.nonNull(userMap.get(contractEntityExt.getCreatorId()))) {
                            creatName = userMap.get(contractEntityExt.getCreatorId()).getName();
                        }
                        data.put(ContractEnum.CREATOR_ID.getAttr(), creatName);
                        data.put(ContractEnum.ADD_TIME.getAttr(), waitPurchaseProductEntity.getAddTime());
                        data.put(ContractEnum.UPDATE_TIME.getAttr(), waitPurchaseProductEntity.getUpdateTime());
                        // data中放入合同数据的创建人 负责人协同人数据 为了后面可见权限用
                        data.put("contractCreatId", contractEntityExt.getCreatorId());
                        // data塞入合同产品数据
                        //多单位处理
                        String unit = waitPurchaseProductEntity.getProductUnit();
                        Long businessUnit = waitPurchaseProductEntity.getBusinessUnit();
                        if (Objects.nonNull(businessUnit)){
                            unit = businessUnit.toString();
                            rate = waitPurchaseProductEntity.getRate();
                        }
                        data.put(ContractProductEnum.UNIT.getAttr(), unitItemMap.getOrDefault(unit, Objects.nonNull(unit) && (!ItemUtil.isUUID(unit) || !RegexUtil.isOnePositiveInt(unit.toString())) ? unit : ""));
                        if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                            Long productUnit = productData.getLong(ProductEnum.UNIT.getAttr());
                            data.put(ProductConstant.TRANSFORM_UNIT_RATE, groupItemsMap.get(productUnit));
                            data.put("enableMultiUnit", BasicConstant.ONE);
                            if (!StringUtil.isDigital(unit) || Long.parseLong(unit) < ProductConstant.MAX_SINGLE_UNIT_VALUE) {
                                MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(productUnit);
                                if (Objects.nonNull(multiUnitItemPoJo)) {
                                    data.put(ContractProductEnum.UNIT.getAttr(), multiUnitItemPoJo.getBaseName());
                                }
                            }
                        }
                        data.put(ContractProductEnum.NUM.getAttr(), contractProductData.get(ContractProductEnum.NUM.getAttr()) == null ? null:Arith.div(contractProductData.getDouble(ContractProductEnum.NUM.getAttr()),rate));
                        data.put(ContractProductEnum.MEMO.getAttr(), contractProductData.get(ContractProductEnum.MEMO.getAttr()));
                        data.put(ContractProductEnum.WAIT_OUTSTOCK_NUM.getAttr(), contractProductData.get(ContractProductEnum.WAIT_OUTSTOCK_NUM.getAttr()) == null ? null : Arith.div(contractProductData.getDouble(ContractProductEnum.WAIT_OUTSTOCK_NUM.getAttr()),rate));
                        // data塞入产品创建人 负责人数据 为了后面可见权限用
                        data.put("productCreatId", productEntityExt.getCreatorId());
                        data.put("productOwnerId", "");
                        // data塞入拼装数据
                        // 已采购数量 已入库数量 已出库数量 建议采购量 以销定采明细 库存查询
                        // 已采购数量 针对该合同下的该产品 所建的采购合同的数量
                        data.put("purchaseNum", Arith.div(purchaseByContractMap.getOrDefault(onlyKey, 0D),rate));
                        // 已入库数量 针对该合同下的该产品 所建的采购合同下的采购入库单数量
                        data.put("instockNum", Arith.div(purchaseInstockMap.getOrDefault(onlyKey,0D),rate));
                        // 已出库数量 该合同下的销售出库单数量
                        data.put("outstockNum", waitPurchaseProductEntity.getContractOutstockNum() == null ? null:Arith.div(waitPurchaseProductEntity.getContractOutstockNum(),rate));
                        // 未出库数量 合同订单数量 - 已出库数量
                        data.put("waitOutstockNum", Arith.div(Arith.sub(waitPurchaseProductEntity.getProductNum(), waitPurchaseProductEntity.getContractOutstockNum()),rate));
                        // 建议采购量 = 合同总量 - 采购总量 - 超发库存总量
                        double purchaseSumNum = 0D;
                        if (!purchaseByContractMap.isEmpty() && purchaseByContractMap.containsKey(onlyKey)) {
                            purchaseSumNum = purchaseByContractMap.get(onlyKey);
                        }
                        // 超发库存总量
                        double exceedNum = 0D;
                        if (!exceedStockMap.isEmpty() && exceedStockMap.containsKey(onlyKey)) {
                            exceedNum = exceedStockMap.get(onlyKey);
                        }
                        // 新公式: 建议采购量 = 合同总量 - 采购总量 - 超发库存总量
                        double shortageQuantity = Arith.sub(waitPurchaseProductEntity.getProductNum(), Arith.add(purchaseSumNum, exceedNum));
                        if (shortageQuantity <= 0) {
//                            continue;
                        }
//                        if (Objects.nonNull(waitPurchaseProductEntity.getBusinessUnit())) {
//                            List<UnitItemPoJo> unitItemPoJos = groupItemsMap.get(waitPurchaseProductEntity.getGroupId());
//                            if (CollectionsUtil.isNotEmpty(unitItemPoJos)) {
//                                accuary = unitItemPoJos.get(0).getAccuracy();
//                            }
//                            waitPurchaseProductEntity.setProductUnit(waitPurchaseProductEntity.getBusinessUnit().toString());
//                            shortageQuantity = Arith.div(shortageQuantity, waitPurchaseProductEntity.getRate(), accuary);
//                        }
                        data.put("advisePurchaseNum", shortageQuantity);
                        data.put("num", shortageQuantity);
                        data.put("purchaseDetail", "查看全部");
                        data.put("stockSearch", "查看全部");
                        if (isEnglish){
                            data.put("purchaseDetail", "view all");
                            data.put("stockSearch", "view all");
                        }
                        // 多选需要
                        data.put("productId", waitPurchaseProductEntity.getId());
                        data.put("contractProductId", waitPurchaseProductEntity.getId());
                        data.put("refProductId", productId);
                        data.put("id", productEntityExt.getId());
                        data.put("contractId", contractEntityExt.getId());
                        // 塞入一键采购按钮
                        List<ButtonPojo> optionList = new ArrayList<>();
                        optionList.add(new ButtonPojo(ListOptionTabEnum.PURCHASE, XbbRefTypeEnum.PURCHASE.getCode()));
                        JSONObject option = new JSONObject();
                        option.put("value", optionList);
                        data.put(ListOptionEnum.OPTION.getAttr(), option);
                        data.put("stockSearchId", productEntityExt.getId());

                        // 移动端特殊处理
                        if (isDingtalk) {
                            data.put(ProductEnum.NAME.getSaasAttr(), productData.getString(ProductEnum.NAME.getAttr()));
                            data.put(ProductEnum.SERIALNO.getAttr(), productData.getString(productEntityExt.getSerialNo()));
                            data.put(ContractEnum.NAME.getAttr(), contractData.getString(ContractEnum.NAME.getAttr()));
                        }

                        PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
                        paasFormDataEntityExt.setData(data);
                        paasFormDataEntityExt.setSourceData(data);
                        paasFormDataEntityExt.setDataId(contractId);
                        // 移动端产品视图列表页需要
                        paasFormDataEntityExt.setId(productEntityExt.getId());
                        paasFormDataESList.add(paasFormDataEntityExt);
                    }
                }
            }
        }
        formDataListVO.setPaasFormDataESList(paasFormDataESList);
        // 处理列表页字段排序
        formDataListSearchHelp.explainFieldSort(formDataListDTO, formDataListVO);
        //表单冻结和隐藏列设置（在按钮设置后处理，防止操作列无法冻结和隐藏）
        formDataListSearchHelp.setFixedAndInvisible(formDataListDTO, formDataListVO);
        // 处理列表数据可见
        praseCanseeWaitPurchaseProductData(formDataListDTO,formDataListVO,needCanSeeExplainMap,contractIdList);
        return formDataListVO;
    }


    public void handleHeadList(List<FieldAttrEntity> headList,boolean isEnglish){
        // 已采购数量
        FieldAttrEntity purchaseNumField = new FieldAttrEntity();
        purchaseNumField.setAttr("purchaseNum");
        purchaseNumField.setSaasAttr("yetPurchaseNum");
        purchaseNumField.setAttrName("已采购数量");
        purchaseNumField.setFieldType(FieldTypeEnum.NUM.getType());
        purchaseNumField.setVisible(1);
        purchaseNumField.setDisableListSort(1);
        // 已入库数量
        FieldAttrEntity instockNumField = new FieldAttrEntity();
        instockNumField.setAttr("instockNum");
        instockNumField.setSaasAttr("yetInstockNum");
        instockNumField.setAttrName("已入库数量");
        instockNumField.setFieldType(FieldTypeEnum.NUM.getType());
        instockNumField.setVisible(1);
        instockNumField.setDisableListSort(1);
        // 出库数量
        FieldAttrEntity outstockNumField = new FieldAttrEntity();
        outstockNumField.setAttr("outstockNum");
        outstockNumField.setSaasAttr("yetOutstockNum");
        outstockNumField.setAttrName("出库数量");
        outstockNumField.setFieldType(FieldTypeEnum.NUM.getType());
        outstockNumField.setVisible(1);
        outstockNumField.setDisableListSort(1);
        // 未出库数量
        FieldAttrEntity waitOutstockNumField = new FieldAttrEntity();
        waitOutstockNumField.setAttr("waitOutstockNum");
        waitOutstockNumField.setSaasAttr("notOutstockNum");
        waitOutstockNumField.setAttrName("未出库数量");
        waitOutstockNumField.setFieldType(FieldTypeEnum.NUM.getType());
        waitOutstockNumField.setVisible(1);
        waitOutstockNumField.setEditable(0);
        waitOutstockNumField.setDisableListSort(1);
        // 建议采购量
        FieldAttrEntity advisePurchaseNumField = new FieldAttrEntity();
        advisePurchaseNumField.setAttr("advisePurchaseNum");
        advisePurchaseNumField.setSaasAttr("waitPurchaseAdviseNum");
        advisePurchaseNumField.setAttrName("建议采购量");
        advisePurchaseNumField.setFieldType(FieldTypeEnum.SMART_REPLENISHMENT_ADVISE.getType());
        advisePurchaseNumField.setVisible(1);
        advisePurchaseNumField.setDisableListSort(1);
        // 以销定采明细
        FieldAttrEntity purchaseDetailField = new FieldAttrEntity();
        purchaseDetailField.setAttr("purchaseDetail");
        purchaseDetailField.setAttr("purchaseDetail");
        purchaseDetailField.setAttrName("以销定购明细");
        purchaseDetailField.setFieldType(FieldTypeEnum.WAIT_PURCHASE_DETAIL.getType());
        purchaseDetailField.setVisible(1);
        // 库存查询
        FieldAttrEntity stockSearchField = new FieldAttrEntity();
        stockSearchField.setAttr("stockSearch");
        stockSearchField.setAttr("stockSearch");
        stockSearchField.setAttrName("库存查询");
        stockSearchField.setFieldType(FieldTypeEnum.WAIT_PURCHASE_DETAIL.getType());
        stockSearchField.setVisible(1);
        if(isEnglish){
            purchaseNumField.setAttrName("purchaseNum");
            stockSearchField.setAttrName("stockSearch");
            purchaseDetailField.setAttrName("purchaseDetail");
            advisePurchaseNumField.setAttrName("advisePurchaseNum");
            waitOutstockNumField.setAttrName("waitOutstockNum");
            outstockNumField.setAttrName("outstockNum");
            instockNumField.setAttrName("instockNum");
        }
        headList.add(purchaseNumField);
        headList.add(instockNumField);
        headList.add(outstockNumField);
        headList.add(waitOutstockNumField);
        headList.add(advisePurchaseNumField);
        headList.add(purchaseDetailField);
        headList.add(stockSearchField);
        Iterator<FieldAttrEntity> iterator = headList.iterator();
        List<FieldAttrEntity> contractAttrList = new ArrayList<>();
        while (iterator.hasNext()){
            FieldAttrEntity next = iterator.next();
            if (Objects.equals(ContractEnum.CONTRACT_NO.getAttr(),next.getAttr())
                || Objects.equals(ContractEnum.NAME.getAttr(),next.getAttr())
                || Objects.equals(ContractEnum.LINK_CUSTOMER.getAttr(),next.getAttr())
                || Objects.equals(ContractEnum.CREATOR_ID.getAttr(),next.getAttr())
                || Objects.equals(ContractEnum.ADD_TIME.getAttr(),next.getAttr())
                || Objects.equals(ContractEnum.UPDATE_TIME.getAttr(),next.getAttr())
                || Objects.equals(ContractProductEnum.UNIT.getAttr(),next.getAttr())
                || Objects.equals(ContractProductEnum.NUM.getAttr(),next.getAttr())
                || Objects.equals(ContractProductEnum.MEMO.getAttr(),next.getAttr())){
                contractAttrList.add(next);
                iterator.remove();
            }
        }
        headList.addAll(contractAttrList);
    }


    public Map<String,List<FieldAttrEntity>> handleWaitPurchaseProductHead(String corpid, List<FieldAttrEntity> headList) throws XbbException{
        Map<String, List<FieldAttrEntity>> needCanSeeExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<FieldAttrEntity> contractFieldList = new ArrayList<>();
        List<FieldAttrEntity> productFieldList = new ArrayList<>();
        // 应产品要求 解释按照原来的逻辑 用第一个合同的为准
        // 根据corpid以及businesstype拿出第一个合同解释 用来设置表头是否展示 数据是否隐藏
        PaasFormExplainEntity paasFormExplainEntity = null;
        Map<String,FieldAttrEntity> contractExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String, Object> paasFormParam = new HashMap<>();
        paasFormParam.put("corpid", corpid);
        paasFormParam.put("enable", 1);
        paasFormParam.put("del", 0);
        paasFormParam.put("distributorMark", DistributorMarkEnum.OTHER.getCode());
        paasFormParam.put("businessType", XbbRefTypeEnum.CONTRACT.getCode());
        paasFormParam.put("orderByStr", "sort ASC ");
        List<PaasFormEntity> paasFormEntityList = paasFormModel.findEntity(paasFormParam);
        if (CollectionsUtil.isNotEmpty(paasFormEntityList)){
            Long formId = paasFormEntityList.get(0).getId();
            paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        }
        if (Objects.nonNull(paasFormExplainEntity)){
            List<FieldAttrEntity> fieldAttrEntityList = JSONObject.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            fieldAttrEntityList.forEach(item ->contractExplainMap.put(item.getAttr(),item));
        }
        // 合同名称 合同编号穿透
        contractExplainMap.entrySet().forEach(item ->{
            if (Objects.equals(item.getKey(),ContractEnum.CONTRACT_NO.getAttr()) || Objects.equals(item.getKey(),ContractEnum.NAME.getAttr())){
                item.getValue().setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
                item.getValue().setDisableListSort(1);
            }
            if (Objects.equals(item.getKey(),ContractEnum.LINK_CUSTOMER.getAttr())){
                item.getValue().setDisableListSort(1);
            }
        });
        // 操作表头
        FieldAttrEntity optionAttrOption = new FieldAttrEntity();
        optionAttrOption.setAttr(ListOptionEnum.OPTION.getAttr());
        optionAttrOption.setAttrName(ListOptionEnum.OPTION.getAttrName());
        optionAttrOption.setFieldType(FieldTypeEnum.OPTION.getType());
        headList.add(optionAttrOption);
        headList.add(contractExplainMap.get(ContractEnum.CONTRACT_NO.getAttr()));
        headList.add(contractExplainMap.get(ContractEnum.NAME.getAttr()));
        headList.add(contractExplainMap.get(ContractEnum.LINK_CUSTOMER.getAttr()));
        headList.add(contractExplainMap.get(ContractEnum.CREATOR_ID.getAttr()));
        headList.add(contractExplainMap.get(ContractEnum.ADD_TIME.getAttr()));
        headList.add(contractExplainMap.get(ContractEnum.UPDATE_TIME.getAttr()));
        // 合同编号 合同名称 客户名称 创建人 创建时间 更新时间
        contractFieldList.add(contractExplainMap.get(ContractEnum.CONTRACT_NO.getAttr()));
        contractFieldList.add(contractExplainMap.get(ContractEnum.NAME.getAttr()));
        contractFieldList.add(contractExplainMap.get(ContractEnum.LINK_CUSTOMER.getAttr()));
        contractFieldList.add(contractExplainMap.get(ContractEnum.CREATOR_ID.getAttr()));
        contractFieldList.add(contractExplainMap.get(ContractEnum.ADD_TIME.getAttr()));
        contractFieldList.add(contractExplainMap.get(ContractEnum.UPDATE_TIME.getAttr()));
        // 处理合同中产品解释 单位 备注 数量 未出库数量
        FieldAttrEntity contractProductEntity = contractExplainMap.get(ContractEnum.PRODUCT.getAttr());
        List<FieldAttrEntity> items = (List<FieldAttrEntity>) contractProductEntity.getSubForm().getItems();
        items.forEach(item ->{
            if (Objects.equals(ContractProductEnum.UNIT.getAttr(),item.getAttr())){
                contractFieldList.add(item);
                headList.add(item);
            } else if (Objects.equals(ContractProductEnum.MEMO.getAttr(),item.getAttr()) ||
                    Objects.equals(ContractProductEnum.NUM.getAttr(),item.getAttr())){
                item.setEditable(0);
                if (Objects.equals(ContractProductEnum.NUM.getAttr(),item.getAttr())){
                    item.setSaasAttr("productNum");
                    item.setAttrName("销售数量");
                }
                contractFieldList.add(item);
                headList.add(item);
            }
            if (Objects.equals(ContractProductEnum.OUTSTOCK_NUM.getAttr(),item.getAttr()) || Objects.equals(ContractProductEnum.WAIT_OUTSTOCK_NUM.getAttr(),item.getAttr()) ){
                item.setVisible(1);
                item.setDisableListSort(1);
                contractFieldList.add(item);
            }
        });
        PaasFormExplainEntity productPaasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        Map<String,FieldAttrEntity> productExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.nonNull(productPaasFormExplainEntity)){
            List<FieldAttrEntity> fieldAttrEntityList = JSONObject.parseArray(productPaasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            fieldAttrEntityList.forEach(item ->{
                // 产品名称 产品编号attr与合同名称编号的attr冲突 穿透
                if (Objects.equals(item.getAttr(),ProductEnum.SERIALNO.getAttr())){
                    item.setAttr("productSerialNo");
                    item.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
                }
                if (Objects.equals(item.getAttr(),ProductEnum.NAME.getAttr())){
                    item.setAttr("productName");
                    item.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
                }
                productExplainMap.put(item.getAttr(),item);
            });
        }
        productFieldList.add(productExplainMap.get(ProductEnum.PRODUCT_IMGS.getAttr()));
        productFieldList.add(productExplainMap.get("productName"));
        productFieldList.add(productExplainMap.get("productSerialNo"));
        productFieldList.add(productExplainMap.get(ProductEnum.SPECIFICATION.getAttr()));
        productFieldList.add(productExplainMap.get(ProductEnum.SUPPLIER.getAttr()));
        headList.add(productExplainMap.get(ProductEnum.PRODUCT_IMGS.getAttr()));

        FieldAttrEntity productNameAttrEntity = productExplainMap.get("productName");
        headList.add(productNameAttrEntity);
        FieldAttrEntity productNoEntity = productExplainMap.get("productSerialNo");
        headList.add(productNoEntity);
        headList.add(productExplainMap.get(ProductEnum.SPECIFICATION.getAttr()));
        headList.add(productExplainMap.get(ProductEnum.SUPPLIER.getAttr()));
        needCanSeeExplainMap.put("contract",contractFieldList);
        needCanSeeExplainMap.put("product",productFieldList);
        return needCanSeeExplainMap;
    }


    /**
     * @Author: wujian
     * @Description: 处理智能补货表头
     * @Date: 下午2:50 2021/11/12
     * @Param: [corpid]
     * @return: java.util.List<com.xbongbong.paas.field.FieldAttrEntity>
     **/
    public List<FieldAttrEntity> handelSmartReplenishmentHeadList(Map<String,FieldAttrEntity> productExplainMap, boolean enablePurchasePassage , boolean enableMiniStock) throws XbbException {
        List<FieldAttrEntity> headList = new ArrayList<>();
        // 库存数量
        FieldAttrEntity optionField = new FieldAttrEntity();
        optionField.setAttr("option_0");
        optionField.setAttrName("操作");
        optionField.setFieldType(FieldTypeEnum.OPTION.getType());
        headList.add(optionField);
        // 产品单位列表设置不可排序
        productExplainMap.get(ProductEnum.UNIT.getAttr()).setDisableListSort(1);
        if(!productExplainMap.isEmpty()){
            headList.add(productExplainMap.get(ProductEnum.PRODUCT_IMGS.getAttr()));
            headList.add(productExplainMap.get(ProductEnum.NAME.getAttr()));
            headList.add(productExplainMap.get(ProductEnum.SERIALNO.getAttr()));
            headList.add(productExplainMap.get(ProductEnum.SPECIFICATION.getAttr()));
            headList.add(productExplainMap.get(ProductEnum.UNIT.getAttr()));
            headList.add(productExplainMap.get(ProductEnum.SUPPLIER.getAttr()));
        }
        // 未出库数量
        FieldAttrEntity waitOutstockNumField = new FieldAttrEntity();
        waitOutstockNumField.setAttr("waitOutstockNum");
        waitOutstockNumField.setAttrName("未出库数量");
        waitOutstockNumField.setAttrNameEn("waitOutstockNum");
        waitOutstockNumField.setFieldType(FieldTypeEnum.NUM.getType());
        waitOutstockNumField.setVisible(1);
        headList.add(waitOutstockNumField);
        if(!productExplainMap.isEmpty()){
            productExplainMap.get(ProductEnum.STOCK.getAttr()).setDisableListSort(0);
            headList.add(productExplainMap.get(ProductEnum.STOCK.getAttr()));
        }
        // 采购在途数量
        if(enablePurchasePassage){
            FieldAttrEntity pendingInstockNumField = new FieldAttrEntity();
            pendingInstockNumField.setAttr("pendingInstockNum");
            pendingInstockNumField.setAttrName("待入库数量");
            pendingInstockNumField.setAttrNameEn("pendingInstockNum");
            pendingInstockNumField.setFieldType(FieldTypeEnum.NUM.getType());
            pendingInstockNumField.setVisible(1);
            pendingInstockNumField.setDisableListSort(1);
            headList.add(pendingInstockNumField);
        }
        if (enableMiniStock){
            // 最低库存
            FieldAttrEntity miniNumField = new FieldAttrEntity();
            miniNumField.setAttr("miniNum");
            miniNumField.setAttrName("最低库存");
            miniNumField.setAttrNameEn("miniNum");
            miniNumField.setFieldType(FieldTypeEnum.NUM.getType());
            miniNumField.setVisible(1);
            headList.add(miniNumField);
        }
        // 建议采购量
        FieldAttrEntity advisePurchaseNumField = new FieldAttrEntity();
        advisePurchaseNumField.setAttr("advisePurchaseNum");
        advisePurchaseNumField.setAttrName("建议采购量");
        advisePurchaseNumField.setAttrNameEn("advisePurchaseNum");
        advisePurchaseNumField.setFieldType(FieldTypeEnum.NUM.getType());
        advisePurchaseNumField.setVisible(1);
        advisePurchaseNumField.setFieldType(FieldTypeEnum.SMART_REPLENISHMENT_ADVISE.getType());
        headList.add(advisePurchaseNumField);
        return headList;
    }

    /**
     * @Author: wujian
     * @Description: 获取智能补货数据
     * @Date:  2021/11/15
     * @Param: [formDataListDTO, count 数据总量, enablePurchasePassage 开启采购在途数量, enableMiniStock 开启最低库存]
     * @return: java.util.List<com.xbongbong.saas.domain.entity.SmartReplenishmentEntity>
     **/
    public List<SmartReplenishmentEntity> getSmartReplenishmentList(FormDataListDTO formDataListDTO, boolean enablePurchasePassage, boolean enableMiniStock) throws XbbException {
        String corpid = formDataListDTO.getCorpid();
        Integer page = formDataListDTO.getPage() == null ? 1 : formDataListDTO.getPage();
        Integer pageSize = formDataListDTO.getPageSize() == null ? PageConstant.DEFAULT_PAGE_SIZE : formDataListDTO.getPageSize();
        List<Long> conditionProductIdList = new ArrayList<>();
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        Map<String, String> sortMap = formDataListDTO.getSortMap();
        String nameLike = formDataListDTO.getNameLike();
        List<Long> idIn = formDataListDTO.getIdIn();
        if (CollectionsUtil.isNotEmpty(idIn)){
            conditionProductIdList.addAll(idIn);
        }
        Boolean showAllProduct = false;
        if (CollectionsUtil.isNotEmpty(conditionList)){
            for (ConditionsEntityExt conditionsEntityExt : conditionList) {
                if (Objects.equals(InventoryEnum.PRODUCT.getAttr(),conditionsEntityExt.getAttr())){
                    List<Object> value = conditionsEntityExt.getValue();
                    if (CollectionsUtil.isNotEmpty(value)){
                        for (Object obj : value) {
                            conditionProductIdList.add(Long.valueOf(obj.toString()));
                        }
                    }
                }
                // 展示全部产品筛选用的产品解释里面的是否预警的attr
                if (Objects.equals(ProductEnum.IS_NOTIFY.getAttr(),conditionsEntityExt.getAttr())){
                    List<Object> value = conditionsEntityExt.getValue();
                    if (CollectionsUtil.isNotEmpty(value)){
                        Integer isShowAllProduct = Integer.valueOf(value.get(0).toString());
                        if(Objects.equals(BasicConstant.ONE,isShowAllProduct)){
                            showAllProduct = true;
                        }
                    }
                }
            }
        }
        UserVO loginUser = formDataListDTO.getLoginUser();
        boolean isBoss = loginUser.isAdminOrBoss();
        // 获取数据可见权限useridIn
        List<Long> depIdIn = new ArrayList<>();
        Set<DepartmentVO> depSet = loginUser.getDepSet();
        //本人部门
        for (DepartmentVO departmentVO : depSet){
            depIdIn.add(departmentVO.getId());
        }
        //父部门
        List<Long> deptIds = departmentModel.getSupDepIdList(corpid, depIdIn, true);

        List<SmartReplenishmentEntity> smartReplenishmentEntityList;
        Map<String,Object> param = new HashMap<>();
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("corpid", corpid);
        param.put("start", (page - 1) * pageSize);
        param.put("pageNum", pageSize);
        if (CollectionsUtil.isNotEmpty(conditionProductIdList)){
            param.put("productIdIn",conditionProductIdList);
        }
        if (showAllProduct){
            param.put("haveZero",1);
        }
        if (Objects.nonNull(nameLike)){
            param.put("nameLike",nameLike);
        }

        // 不是超管的话 放入userid及部门id 用于数据查询
        if (!isBoss){
            param.put("isBoss",0);
            param.put("userId",loginUser.getUserId());
            param.put("depts",deptIds);
        }
        // 默认按照更新时间
        param.put("orderByStr","update_time DESC");
        // 列表页设置的默认排序
        Long appId = formDataListDTO.getAppId();
        Long formId = formDataListDTO.getFormId();
        String  key = UserConfigEnum.DEFAULT_SORT_FIELD.getAlias() + "_" + appId + "_" + formId;
        Map<String, Object> params = BeanUtil.convertBean2Map(formDataListDTO, true);
        List<String> configAliasList = new ArrayList<>();
        configAliasList.add(key);
        params.put("configAliasIn", configAliasList);
        params.put("userId", formDataListDTO.getUserId());
        params.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        List<UserConfigEntity> userConfigList = userConfigModel.list(params);
        if (CollectionUtils.isNotEmpty(userConfigList)){
            String configValue = userConfigList.get(0).getConfigValue();
            JSONObject jsonObject = JSONObject.parseObject(configValue);
            String sortType = jsonObject.getString("sortType");
            if(Objects.isNull(sortType)){
                sortType = "desc";
            }
            String sortAttr = jsonObject.getString("sortAttr");
            if (StringUtil.isNotEmpty(sortAttr)){
                if (Objects.equals(sortAttr,ProductEnum.NAME.getAttr())){
                    param.put("orderByStr","product_name" + " " + sortType );
                }else if (Objects.equals(sortAttr,ProductEnum.SERIALNO.getAttr())){
                    param.put("orderByStr","product_no" + " " + sortType);
                }else if (Objects.equals(sortAttr,ProductEnum.STOCK.getAttr())){
                    param.put("orderByStr","stock_num" + " " + sortType);
                }else if (Objects.equals(sortAttr,"miniNum")){
                    param.put("orderByStr","mini_num" + " " + sortType );
                } else if (Objects.equals(sortAttr,"waitOutstockNum")){
                    param.put("orderByStr","wait_outstock_num" + " " + sortType );
                }
            }
        }

        // 列表页点击排序
        if (!sortMap.isEmpty() &&  Objects.nonNull(sortMap.get("field"))){
            String field = sortMap.get("field");
            String sort = sortMap.get("sort");
            if (Objects.equals(sort,"desc")){
                if (Objects.equals(field,ProductEnum.NAME.getAttr())){
                    param.put("orderByStr","product_name DESC");
                }else if (Objects.equals(field,ProductEnum.SERIALNO.getAttr())){
                    param.put("orderByStr","product_no DESC");
                }else if (Objects.equals(field,"stockNum")){
                    param.put("orderByStr","stock_num DESC");
                }else if (Objects.equals(field,"miniNum")){
                    param.put("orderByStr","mini_num DESC");
                } else if (Objects.equals(field,"waitOutstockNum")){
                    param.put("orderByStr","wait_outstock_num DESC");
                }else if (Objects.equals(field,"addTime")){
                    param.put("orderByStr","add_time DESC");
                }
            }else {
                if (Objects.equals(field,ProductEnum.NAME.getAttr())){
                    param.put("orderByStr","product_name asc");
                }else if (Objects.equals(field,ProductEnum.SERIALNO.getAttr())){
                    param.put("orderByStr","product_no asc");
                }else if (Objects.equals(field,"stockNum")){
                    param.put("orderByStr","stock_num asc");
                }else if (Objects.equals(field,"miniNum")){
                    param.put("orderByStr","mini_num asc");
                } else if (Objects.equals(field,"waitOutstockNum")) {
                    param.put("orderByStr","wait_outstock_num asc");
                }else if (Objects.equals(field,"addTime")){
                    param.put("orderByStr","add_time asc");
                }else if (Objects.equals(field,"updateTime")){
                    param.put("orderByStr","update_time asc");
                }
            }
        }

        if (enablePurchasePassage && !enableMiniStock){
            // 启用采购在途 未启用最低库存
            smartReplenishmentEntityList = smartReplenishmentModel.getEnablePurchasePassage(param);
        }else if (!enablePurchasePassage && enableMiniStock){
            // 未启用采购在途 启用了最低库存
            smartReplenishmentEntityList = smartReplenishmentModel.getEnableMiniStock(param);
        }else if (enablePurchasePassage && enableMiniStock){
            // 启用采购在途 且启用了最低库存
            smartReplenishmentEntityList = smartReplenishmentModel.getAllEnable(param);
        }else {
            // 都未启用
            smartReplenishmentEntityList = smartReplenishmentModel.getAllNotEnable(param);
        }
        return smartReplenishmentEntityList;
    }

    public Integer getSmartReplenishmentCount(FormDataListDTO formDataListDTO, boolean enablePurchasePassage, boolean enableMiniStock){
        String corpid = formDataListDTO.getCorpid();
        Integer count  = 1;
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        Boolean showAllProduct = false;
        if (CollectionsUtil.isNotEmpty(conditionList)){
            for (ConditionsEntityExt conditionsEntityExt : conditionList) {
                // 展示全部产品筛选用的产品解释里面的是否预警的attr
                if (Objects.equals(ProductEnum.IS_NOTIFY.getAttr(),conditionsEntityExt.getAttr())){
                    List<Object> value = conditionsEntityExt.getValue();
                    if (CollectionsUtil.isNotEmpty(value)){
                        Integer isShowAllProduct = Integer.valueOf(value.get(0).toString());
                        if(Objects.equals(BasicConstant.ONE,isShowAllProduct)){
                            showAllProduct = true;
                        }
                    }
                }
            }
        }
        String nameLike = formDataListDTO.getNameLike();

        UserVO loginUser = formDataListDTO.getLoginUser();
        boolean isBoss = loginUser.isAdminOrBoss();
        // 获取数据可见权限useridIn
        List<Long> depIdIn = new ArrayList<>();
        Set<DepartmentVO> depSet = loginUser.getDepSet();
        //本人部门
        for (DepartmentVO departmentVO : depSet){
            depIdIn.add(departmentVO.getId());
        }
        //父部门
        List<Long> deptIds =    departmentModel.getSupDepIdList(corpid, depIdIn, true);



        Map<String,Object> countParam = new HashMap<>();
        countParam.put("del", DelEnum.NORMAL.getDel());
        countParam.put("corpid", corpid);
        if (Objects.nonNull(nameLike)){
            countParam.put("nameLike",nameLike);
        }
        if (showAllProduct){
            countParam.put("haveZero",1);
        }
        // 不是超管的话 放入userid及部门id 用于数据查询
        if (!isBoss){
            countParam.put("isBoss",0);
            countParam.put("userId",loginUser.getUserId());
            countParam.put("depts",deptIds);
        }
        if (enablePurchasePassage && !enableMiniStock){
            // 启用采购在途 未启用最低库存
            count = smartReplenishmentModel.countEnablePurchasePassage(countParam);
        }else if (!enablePurchasePassage && enableMiniStock){
            // 未启用采购在途 启用了最低库存
            count = smartReplenishmentModel.countEnableMiniStock(countParam);

        }else if (enablePurchasePassage && enableMiniStock){
            // 启用采购在途 且启用了最低库存
            count = smartReplenishmentModel.countAllEnable(countParam);
        }else {
            // 都未启用
            count = smartReplenishmentModel.countAllNotEnable(countParam);
        }
        return count;
    }

    public void handelSaasSpecialList(List<FieldAttrEntity> explainList, Integer businessType, Integer subBusinessType) {
        if (Objects.isNull(businessType) || Objects.isNull(subBusinessType)){
            return;
        }
        SaasSpecialListEnum saasSpecialListEnum = SaasSpecialListEnum.getByBusinessType(subBusinessType);
        Iterator<FieldAttrEntity> iterator = explainList.iterator();
        switch (saasSpecialListEnum) {
            case CUSTOMER:
            case CUSTOMER_DEAL:
            case CUSTOMER_FOLLOW:
            case CUSTOMER_FOCUS:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if (Objects.equals(attr, CustomerManagementEnum.BACK_PUBLIC_DATE.getAttr())) {
                        iterator.remove();
                        break;
                    }
                }
                break;
            case CUSTOMER_PUBLIC:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if (Objects.equals(attr, CustomerManagementEnum.DISTRIBUTION_DATE.getAttr()) || Objects.equals(attr, CustomerManagementEnum.COUSERID.getAttr())) {
                        iterator.remove();
                    }
                    if (Objects.equals(attr, CustomerManagementEnum.OWNER_ID.getAttr())) {
                        fieldAttrEntity.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.PRE_OWNER_ID));
                    }
                }
                break;
            case CUSTOMER_RECYCLE:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if (Objects.equals(attr, CustomerManagementEnum.BACK_PUBLIC_DATE.getAttr()) || Objects.equals(attr, CustomerManagementEnum.DISTRIBUTION_DATE.getAttr())
                            || Objects.equals(attr, CustomerManagementEnum.OWNER_ID.getAttr()) || Objects.equals(attr, CustomerManagementEnum.COUSERID.getAttr())) {
                        iterator.remove();
                    }
                }
                break;
            case ALL_CLUE:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if (Objects.equals(attr, ClueEnum.BACK_PUBLIC_DATE.getAttr())) {
                        iterator.remove();
                        break;
                    }
                }
                break;
            case CLUE_PUBLIC:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if (Objects.equals(attr, ClueEnum.DISTRIBUTION_DATE.getAttr()) || Objects.equals(attr, ClueEnum.COUSERID.getAttr())) {
                        iterator.remove();
                    }
                    if (Objects.equals(attr, ClueEnum.OWNER_ID.getAttr())) {
                        fieldAttrEntity.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.PRE_OWNER_ID));
                    }
                }
                break;
            case CLUE_RECYCLE:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if (Objects.equals(attr, ClueEnum.BACK_PUBLIC_DATE.getAttr()) || Objects.equals(attr, ClueEnum.DISTRIBUTION_DATE.getAttr())
                            || Objects.equals(attr, ClueEnum.OWNER_ID.getAttr()) || Objects.equals(attr, ClueEnum.COUSERID.getAttr())) {
                        iterator.remove();
                    }
                }
                break;
            case WAITINSTOCK:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if (!(Objects.equals(attr, WaitInstockEnum.SHEET_NO.getAttr())
                            || Objects.equals(attr, WaitInstockEnum.PURCHASE_NAME.getAttr())
                            || Objects.equals(attr, WaitInstockEnum.SUPPLIER_ID.getAttr())
                            || Objects.equals(attr, WaitInstockEnum.SIGN_TIME.getAttr())
                            || Objects.equals(attr, WaitInstockEnum.ESTIMATE_ARRIVE_TIME.getAttr())
                            || Objects.equals(attr, WaitInstockEnum.STATUS.getAttr())
                            || Objects.equals(attr, WaitInstockEnum.SIGNER_ID.getAttr())
                            || Objects.equals(attr, WaitInstockEnum.UPDATETIME.getAttr())
                            || Objects.equals(attr, WaitInstockEnum.ADDTIME.getAttr()))) {
                        iterator.remove();
                    }
                    if(Objects.equals(fieldAttrEntity.getAttr(),WaitInstockEnum.SUPPLIER_ID.getAttr())){
                        fieldAttrEntity.setAttrName(WaitInstockEnum.SUPPLIER_ID.getAttrName());
                    }
                    fieldAttrEntity.setEditable(0);
                }
                break;
            case WAITOUTSTOCK:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if (!(Objects.equals(attr, ContractEnum.NAME.getAttr())
                            || Objects.equals(attr, ContractEnum.CONTRACT_NO.getAttr())
                            || Objects.equals(attr, ContractEnum.LINK_CUSTOMER.getAttr())
                            || Objects.equals(attr, ContractEnum.STATUS.getAttr())
                            || Objects.equals(attr, ContractEnum.SIGN_TIME.getAttr())
                            || Objects.equals(attr, ContractEnum.OWNER_ID.getAttr())
                            || Objects.equals(attr, ContractEnum.MINOR_USER.getAttr())
                            || Objects.equals(attr, FieldTypeEnum.ADDTIME.getAlias())
                            || Objects.equals(attr, FieldTypeEnum.UPDATETIME.getAlias())
                            || Objects.equals(attr, FieldTypeEnum.CREATORID.getAlias()))) {
                        iterator.remove();
                    }
                    fieldAttrEntity.setEditable(0);
                }
                break;
            case WAITPRODUCE:
                if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                    while (iterator.hasNext()) {
                        FieldAttrEntity fieldAttrEntity = iterator.next();
                        String attr = fieldAttrEntity.getAttr();
                        if (!(Objects.equals(attr, ContractEnum.NAME.getAttr())
                                || Objects.equals(attr, ContractEnum.LINK_CUSTOMER.getAttr())
                                || Objects.equals(attr, ContractEnum.CONTRACT_NO.getAttr())
                                || Objects.equals(attr, FieldTypeEnum.ADDTIME.getAlias())
                                || Objects.equals(attr, FieldTypeEnum.UPDATETIME.getAlias())
                                || Objects.equals(attr, FieldTypeEnum.CREATORID.getAlias()))) {
                            iterator.remove();
                        }
                        fieldAttrEntity.setEditable(0);
                    }
                } else if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
                    while (iterator.hasNext()) {
                        FieldAttrEntity fieldAttrEntity = iterator.next();
                        String attr = fieldAttrEntity.getAttr();
                        if (Objects.equals(attr, ProductEnum.STOCK.getAttr())) {
                            fieldAttrEntity.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.OUT_OF_STOCK_NUM));
                        } else if (!(Objects.equals(attr, ProductEnum.NAME.getAttr())
                                || Objects.equals(attr, ProductEnum.PRODUCT_IMGS.getAttr())
                                || Objects.equals(attr, ProductEnum.SPECIFICATION.getAttr())
                                || Objects.equals(attr, ProductEnum.UNIT.getAttr())
                                || Objects.equals(attr, ProductEnum.SUPPLIER.getAttr())
                                || Objects.equals(attr, FieldTypeEnum.ADDTIME.getAlias())
                                || Objects.equals(attr, FieldTypeEnum.UPDATETIME.getAlias())
                                || Objects.equals(attr, FieldTypeEnum.CREATORID.getAlias()))) {
                            iterator.remove();
                        }
                        fieldAttrEntity.setEditable(0);
                    }
                }
                break;
            case WAITPURCHASE:
                if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                    while (iterator.hasNext()) {
                        FieldAttrEntity fieldAttrEntity = iterator.next();
                        String attr = fieldAttrEntity.getAttr();
                        if (!(Objects.equals(attr, ContractEnum.NAME.getAttr())
                                || Objects.equals(attr, ContractEnum.LINK_CUSTOMER.getAttr())
                                || Objects.equals(attr, ContractEnum.CONTRACT_NO.getAttr())
                                || Objects.equals(attr, FieldTypeEnum.ADDTIME.getAlias())
                                || Objects.equals(attr, FieldTypeEnum.UPDATETIME.getAlias())
                                || Objects.equals(attr, FieldTypeEnum.CREATORID.getAlias()))) {
                            iterator.remove();
                        }
                        fieldAttrEntity.setEditable(0);
                    }
                } else if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
                    while (iterator.hasNext()) {
                        FieldAttrEntity fieldAttrEntity = iterator.next();
                        String attr = fieldAttrEntity.getAttr();
                        if (!(Objects.equals(attr, ContractEnum.NAME.getAttr())
                            || Objects.equals(attr, ContractEnum.CONTRACT_NO.getAttr())
                            || Objects.equals(attr, FieldTypeEnum.ADDTIME.getAlias())
                            || Objects.equals(attr, FieldTypeEnum.UPDATETIME.getAlias())
                            || Objects.equals(attr, FieldTypeEnum.CREATORID.getAlias()))) {
                            iterator.remove();
                        }
                        fieldAttrEntity.setEditable(0);
                    }
                }
                break;
            case SMART_REPLENISHMENT:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if (!Objects.equals(attr, "showAllProduct")
                        && !(Objects.equals(attr, ProductEnum.ADD_TIME.getAttr()))
                        && !(Objects.equals(attr, ProductEnum.UPDATE_TIME.getAttr()))) {
                        iterator.remove();
                    }
                    fieldAttrEntity.setEditable(0);
                }
                break;
            case STOCK_SEARCH:
            case GUARANTEE_SEARCH:
            case WARNING_SEARCH:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    if (Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.STOCK.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.COST.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.PRICE.getAttr())) {
                        fieldAttrEntity.setDisableListSort(0);
                    }
                }
                break;
            case KNOWLEDGE_BASE:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if (!(Objects.equals(attr, KnowledgeDataEnum.STATUS.getAttr())
                            || Objects.equals(attr, KnowledgeDataEnum.LABEL.getAttr()))) {
                        iterator.remove();
                    }
                    fieldAttrEntity.setEditable(0);
                }
                break;
            default:
                break;
        }
    }

    public List<ConditionsEntityExt> packageWaitProduceCondition(FormDataListDTO formDataListDTO) throws XbbException {
        if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
            for (ConditionsEntityExt conditionsEntityExt : formDataListDTO.getConditions()) {
                if (Objects.equals(conditionsEntityExt.getAttr(), ProductEnum.SPECIFICATION.getAttr())) {
                    conditionsEntityExt.setAttr(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
                    break;
                }
            }
        }
        List<ContractProductEntity> allContractProductList = contractProductModel.getAllContractProduct(formDataListDTO.getCorpid(),ContractProduceEnum.WAIT_PRODUCE.getCode());
        //每个缺货产品对应的缺货合同订单列表
        Set<Long> dataIdSet = new HashSet<>();
        Set<Long> contractIdSet = new HashSet<>();
        for (ContractProductEntity contractProductEntity : allContractProductList) {
            if (Objects.equals(XbbRefTypeEnum.WAIT_PRODUCE.getCode(), formDataListDTO.getSubBusinessType()) && !Objects.equals(WaitOutStockStatusEnum.NORMAL.getCode(), contractProductEntity.getStatus())) {
                continue;
            }
            contractIdSet.add(contractProductEntity.getContractId());

        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termsQuery(StringConstant.DATA_ID, contractIdSet));
        boolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ARCHIVED), ArchivedEnum.ARCHIVED.getCode()));
        boolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ALL_OUT_BOUND), AllOutBoundEnum.ALL_OUT.getCode()));
        List<ContractEntityExt> contractList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTRACT, boolQueryBuilder, ContractEntityExt.class, Collections.singletonList(StringConstant.SAAS_LINK_BUSINESS_ID));
        List<Long> needShowContractIdList = new ArrayList<>();
        contractList.forEach(entity-> needShowContractIdList.add(entity.getId()));
        List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        for (ContractProductEntity entity : allContractProductList){
            if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.CONTRACT.getCode())){
                dataIdSet.add(entity.getContractId());
                List<PaasFormEntityExt> paasFormEntityExtList = paasFormService.getEnableContractFormList(formDataListDTO.getLoginUser());
                List<Long> formIdList = new ArrayList<>();
                for (PaasFormEntityExt entityExt : paasFormEntityExtList){
                    formIdList.add(entityExt.getId());
                }
                if (formIdList.isEmpty()){
                    formIdList.add(-1L);
                }
                formDataListDTO.setFormIdList(formIdList);
                formDataListDTO.setLimitForms(true);
//                saasListDataPermissionHelp.listDataPermission(conditionsEntityExtList,userEntity,XbbRefTypeEnum.CONTRACT.getCode(), XbbRefTypeEnum.CONTRACT.getCode());
            }else if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
                if (needShowContractIdList.contains(entity.getContractId())) {
                    dataIdSet.add(entity.getProductId());
                }
                List<List<ConditionsEntityExt>> shouldConditionList = new ArrayList<>();
//                saasListDataPermissionHelp.listDepAndUserDataPermission(shouldConditionList,userEntity,XbbRefTypeEnum.PRODUCT.getCode(), formDataListDTO.getLoginUser().getDepSet());
                formDataListDTO.setShouldConditions(shouldConditionList);
            }
        }
        //根据合同id获取分页后的合同列表
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setAttr(FieldTypeEnum.DATAID.getAlias());
        conditionsEntityExt.setFieldType(FieldTypeEnum.DATAID.getType());
        conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
        dataIdSet.add(-1L);
        conditionsEntityExt.setValue(new ArrayList<>(dataIdSet));
        if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.CONTRACT.getCode())){
            conditionsEntityExtList.add(new ConditionsEntityExt(ContractEnum.ARCHIVED.getAttr(),"",ContractEnum.ARCHIVED.getFieldType(),ConditionEnum.EQUAL.getSymbol(),Collections.singletonList(ArchivedEnum.UN_ARCHIVED.getCode())));
            conditionsEntityExtList.add(new ConditionsEntityExt(ContractEnum.ALL_OUT_BOUND.getAttr(),"",ContractEnum.ALL_OUT_BOUND.getFieldType(),ConditionEnum.EQUAL.getSymbol(),Collections.singletonList(AllOutBoundEnum.NON_OUT.getCode())));
            conditionsEntityExtList.add(new ConditionsEntityExt(ContractEnum.SHIP_STATUS.getAttr(),"",ContractEnum.SHIP_STATUS.getFieldType(),ConditionEnum.NOEQUAL.getSymbol(),Collections.singletonList(ShipStatusEnum.CLOSED.getCode())));
        }
        conditionsEntityExtList.add(conditionsEntityExt);
        return conditionsEntityExtList;
    }

    public List<ConditionsEntityExt> packageWaitOutstockCondition(FormDataListDTO formDataListDTO) {
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(), userEntity);
//        saasListDataPermissionHelp.listDataPermission(conditionList, formDataListDTO.getLoginUser() ,XbbRefTypeEnum.CONTRACT.getCode(), XbbRefTypeEnum.CONTRACT.getCode());
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setAttr(ContractEnum.ALL_OUT_BOUND.getAttr());
        conditionsEntityExt.setFieldType(ContractEnum.ALL_OUT_BOUND.getFieldType());
        conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
        conditionsEntityExt.setValue(Collections.singletonList(0));
        ConditionsEntityExt shipConditionsEntityExt = new ConditionsEntityExt();
        shipConditionsEntityExt.setAttr(ContractEnum.SHIP_STATUS.getAttr());
        shipConditionsEntityExt.setFieldType(ContractEnum.SHIP_STATUS.getFieldType());
        shipConditionsEntityExt.setSymbol(ConditionEnum.NOEQUAL.getSymbol());
        shipConditionsEntityExt.setValue(Collections.singletonList(ShipStatusEnum.CLOSED.getCode()));
        ConditionsEntityExt arachivedEntityExt = new ConditionsEntityExt();
        arachivedEntityExt.setAttr(ContractEnum.ARCHIVED.getAttr());
        arachivedEntityExt.setFieldType(ContractEnum.ARCHIVED.getFieldType());
        arachivedEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
        arachivedEntityExt.setValue(Collections.singletonList(ArchivedEnum.UN_ARCHIVED.getCode()));
        ConditionsEntityExt redConditionsEntityExt = new ConditionsEntityExt();
        redConditionsEntityExt.setAttr(ContractEnum.IS_RED.getAttr());
        redConditionsEntityExt.setFieldType(ContractEnum.IS_RED.getFieldType());
        redConditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
        redConditionsEntityExt.setValue(Collections.singletonList(0));
        ConditionsEntityExt productConditionsEntityExt = new ConditionsEntityExt();
        productConditionsEntityExt.setAttr(ContractEnum.PRODUCT.getAttr());
        productConditionsEntityExt.setFieldType(ContractEnum.PRODUCT.getFieldType());
        productConditionsEntityExt.setSymbol(ConditionEnum.NOEMPTY.getSymbol());
        /*UserVO userVO = formDataListDTO.getLoginUser();
        BeanUtil.copyProperties(userVO, userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity);
        List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, userVO.getUserId(), userVO.getCorpid(), BasicConstant.ZERO,false);
        ConditionsEntityExt conditionsEntityFour = new ConditionsEntityExt();
        conditionsEntityFour.setSymbol(ConditionEnum.IN.getSymbol());
        conditionsEntityFour.setValue(new ArrayList<>(userIdIn));
        conditionsEntityFour.setAttr(FieldTypeEnum.TEAM_USER.getAlias());
        conditionsEntityFour.setFieldType(FieldTypeEnum.TEAM_USER.getType());
        conditionList.add(conditionsEntityFour);*/
        conditionList.add(conditionsEntityExt);
        conditionList.add(productConditionsEntityExt);
        conditionList.add(arachivedEntityExt);
        conditionList.add(redConditionsEntityExt);
        conditionList.add(shipConditionsEntityExt);
        if (CollectionsUtil.isNotEmpty(formDataListDTO.getConditions())) {
            Iterator<ConditionsEntityExt> iterator = formDataListDTO.getConditions().iterator();
            while (iterator.hasNext()) {
                ConditionsEntityExt next = iterator.next();
                String attr = next.getAttr();
                List<Object> value = next.getValue();
                if (Objects.equals(attr, "array_2")) {
                    if (CollectionsUtil.isNotEmpty(value)) {
                        // 直接塞入合同ID
                        ConditionsEntityExt contractCondition = new ConditionsEntityExt();
                        contractCondition.setAttr(FieldTypeEnum.ID.getAlias());
                        contractCondition.setFieldType(FieldTypeEnum.DATAID.getType());
                        contractCondition.setSymbol(ConditionEnum.INCLUDE.getSymbol());
                        contractCondition.setValue(value);
                        conditionList.add(contractCondition);
                        iterator.remove();
                    }
                }
            }
        }
        return conditionList;
    }

    public List<ConditionsEntityExt> packageWaitInstockCondition(FormDataListDTO formDataListDTO) {
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
//        saasListDataPermissionHelp.listDataPermission(conditionList,userEntity,XbbRefTypeEnum.PURCHASE.getCode(), XbbRefTypeEnum.PURCHASE.getCode());
        ConditionsEntityExt conditionsEntityOne = new ConditionsEntityExt();
        conditionsEntityOne.setAttr(PurchaseEnum.ALL_INCOMING.getAttr());
        conditionsEntityOne.setFieldType(PurchaseEnum.ALL_INCOMING.getFieldType());
        conditionsEntityOne.setName(PurchaseEnum.ALL_INCOMING.getAttrName());
        conditionsEntityOne.setSubAttr("");
        conditionsEntityOne.setSymbol(ConditionEnum.EQUAL.getSymbol());
        conditionsEntityOne.setValue(Collections.singletonList(0));
        conditionList.add(conditionsEntityOne);
        ConditionsEntityExt instockconditionsTwo = new ConditionsEntityExt();
        instockconditionsTwo.setAttr(PurchaseEnum.RECEIVE_STATUS.getAttr());
        instockconditionsTwo.setFieldType(PurchaseEnum.RECEIVE_STATUS.getFieldType());
        instockconditionsTwo.setName(PurchaseEnum.RECEIVE_STATUS.getAttrName());
        instockconditionsTwo.setSubAttr("");
        instockconditionsTwo.setSymbol(ConditionEnum.NOEQUAL.getSymbol());
        instockconditionsTwo.setValue(Collections.singletonList(ReceiveStatusEnum.CLOSED.getCode()));
        conditionList.add(instockconditionsTwo);
        //兼容采购合同id查询
        List<ConditionsEntityExt> purchaseConditionList = formDataListDTO.getConditions();
        Iterator<ConditionsEntityExt> iterator = purchaseConditionList.iterator();
        while (iterator.hasNext()){
            ConditionsEntityExt conditionsEntity = iterator.next();
            if(Objects.equals(conditionsEntity.getAttr(), "array_2")){
                ConditionsEntityExt conditionsEntityThree = new ConditionsEntityExt();
                conditionsEntityThree.setAttr(FieldTypeEnum.ID.getAlias());
                conditionsEntityThree.setFieldType(FieldTypeEnum.DATAID.getType());
                conditionsEntityThree.setSymbol(ConditionEnum.INCLUDE.getSymbol());
                conditionsEntityThree.setValue(conditionsEntity.getValue());
                conditionList.add(conditionsEntityThree);
                iterator.remove();
            }
        }
        return conditionList;
    }

    public List<ConditionsEntityExt> packagePurchaseCondition(ProductListDataDTO productListDataDTO) {
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(productListDataDTO.getLoginUser(),userEntity);
//        saasListDataPermissionHelp.listDataPermission(conditionList,userEntity,XbbRefTypeEnum.PURCHASE.getCode(), XbbRefTypeEnum.PURCHASE.getCode());
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setAttr(PurchaseEnum.ALL_INCOMING.getAttr());
        conditionsEntityExt.setFieldType(PurchaseEnum.ALL_INCOMING.getFieldType());
        conditionsEntityExt.setName(PurchaseEnum.ALL_INCOMING.getAttrName());
        conditionsEntityExt.setSubAttr("");
        conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
        conditionsEntityExt.setValue(Collections.singletonList(0));
        ConditionsEntityExt instockconditionsEntity = new ConditionsEntityExt();
        instockconditionsEntity.setAttr(PurchaseEnum.RECEIVE_STATUS.getAttr());
        instockconditionsEntity.setFieldType(PurchaseEnum.RECEIVE_STATUS.getFieldType());
        instockconditionsEntity.setName(PurchaseEnum.RECEIVE_STATUS.getAttrName());
        instockconditionsEntity.setSubAttr("");
        instockconditionsEntity.setSymbol(ConditionEnum.NOEQUAL.getSymbol());
        instockconditionsEntity.setValue(Collections.singletonList(ReceiveStatusEnum.CLOSED.getCode()));
        conditionList.add(instockconditionsEntity);
        conditionList.add(conditionsEntityExt);
        ConditionsEntityExt flowConditionsEntity = new ConditionsEntityExt();
        flowConditionsEntity.setAttr(FieldTypeEnum.FLOW_STATUS.getAlias());
        flowConditionsEntity.setFieldType(FieldTypeEnum.FLOW_STATUS.getType());
        flowConditionsEntity.setSubAttr("");
        flowConditionsEntity.setSymbol(ConditionEnum.IN.getSymbol());
        flowConditionsEntity.setValue(Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType()));
        conditionList.add(flowConditionsEntity);
        return conditionList;
    }

    /**
     * 待入库采购合同id条件添加
     * @param purchaseId
     * @return
     * @throws XbbException
     */
    public List<ConditionsEntityExt> purchaseWaitInstockCondition(List purchaseId) {
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        ConditionsEntityExt instockconditionsEntity = new ConditionsEntityExt();
        instockconditionsEntity.setAttr(FieldTypeEnum.ID.getAlias());
        instockconditionsEntity.setFieldType(FieldTypeEnum.DATAID.getType());
        instockconditionsEntity.setSymbol(ConditionEnum.INCLUDE.getSymbol());
        instockconditionsEntity.setValue(purchaseId);
        conditionList.add(instockconditionsEntity);
        return conditionList;
    }

    /**
     * 待采购待生产缺货产品
     * @param corpid
     * @param dataIdList
     * @param subBusinessType
     * @return
     * @throws XbbException
     */
    public Map<Long,List<WaitContractProductPojo>> getWaitContractProductPojoMap(String corpid,List<Long> dataIdList,Integer subBusinessType,Integer isProduce) throws XbbException {
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("columns", "id,any_value(contract_id) as contract_id,any_value(product_id) as product_id,sum(product_num) as product_num,sum(outstock_num) as outstock_num,product_no,product_unit,business_unit,rate,group_id");
        map.put("corpid", corpid);
        map.put("del", 0);
        map.put("contractIdIn", dataIdList);
        map.put("isProduce", isProduce);
        map.put("groupByStr", "contract_id,product_id");
        // 合同状态在待系列正常
        map.put("status", 0);
        //获取合同产品信息
        List<ContractProductEntity> contractProductEntityList = contractProductModel.findEntitys(map);
        // 关联产品按关联产品id升序排序
        contractProductEntityList.sort((o1, o2) -> (int)(o2.getId() - o1.getId()));
        Map<Long, List<ContractProductEntity>> contractProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, PaasFormDataEntityExt> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Long> productIdSet = new HashSet<>();
        for (ContractProductEntity entity : contractProductEntityList) {
            if (Objects.equals(entity.getProductNum(),entity.getOutstockNum())){
                continue;
            }
            List<ContractProductEntity> singleContractProductList = new ArrayList<>();
            singleContractProductList.add(entity);
            productIdSet.add(entity.getProductId());
            if (contractProductMap.containsKey(entity.getContractId())) {
                singleContractProductList.addAll(contractProductMap.get(entity.getContractId()));
            }
            contractProductMap.put(entity.getContractId(), singleContractProductList);
        }
        if (productIdSet.isEmpty()) {
            productIdSet.add(-1L);
        }
//        if (Objects.equals(subBusinessType, XbbRefTypeEnum.WAIT_PURCHASE.getCode())) {
//            outstockProductModel.filterOutstockProduct(contractProductMap, corpid, dataIdList);
//        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(), productIdSet));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        // 限制返回值
        List<String> fieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias(), StringConstant.JSON_DATA, "formId");
        //关联产品的具体信息
        List<PaasFormDataEntityExt> paasFormDataEntityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
        for (PaasFormDataEntityExt entity : paasFormDataEntityExtList) {
            productMap.put(entity.getDataId(), entity);
        }
        Map<String, String> unitItemMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<UnitItemPoJo>> groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
        Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
        List<ItemPoJo> productItems = relativeProductHelp.getBusinessUnitItems(corpid);
        productItems.forEach(item -> {
            if (!Objects.equals(item.getIsOther(), 1)) {
                unitItemMap.put(item.getValue().toString(), item.getText());
            }
        });
        Map<Long, List<WaitContractProductPojo>> waitContractProduceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        int accuary = 6;
        for (Map.Entry<Long, List<ContractProductEntity>> entry : contractProductMap.entrySet()) {
            List<ContractProductEntity> productEntityList = entry.getValue();
            Long contractId = entry.getKey();
            List<WaitContractProductPojo> waitContractProductPojoList = waitContractProduceMap.getOrDefault(contractId, new ArrayList<>());
            for (ContractProductEntity contractProductEntity : productEntityList) {
                Long productId = contractProductEntity.getProductId();
                if (!productMap.containsKey(productId)) {
                    continue;
                }
                JSONObject productData = productMap.get(productId).getData();
                double stock = Objects.isNull(productData.getDouble(ProductEnum.STOCK.getAttr())) ? 0D : productData.getDouble(ProductEnum.STOCK.getAttr());
                double shortageQuantity = Arith.sub(contractProductEntity.getProductNum() , Arith.add(contractProductEntity.getOutstockNum() ,stock));
                if (shortageQuantity <= 0) {
                    continue;
                }
                WaitContractProductPojo waitContractProductPojo = new WaitContractProductPojo();
                if (Objects.nonNull(contractProductEntity.getBusinessUnit())) {
                    List<UnitItemPoJo> unitItemPoJos = groupItemsMap.get(contractProductEntity.getGroupId());
                    if (CollectionsUtil.isNotEmpty(unitItemPoJos)) {
                        accuary = unitItemPoJos.get(0).getAccuracy();
                    }
                    contractProductEntity.setProductUnit(contractProductEntity.getBusinessUnit().toString());
                    shortageQuantity = Arith.div(shortageQuantity, contractProductEntity.getRate(), accuary);
                }
                waitContractProductPojo.setParentId(productData.getLong(ProductEnum.PARENT_ID.getAttr()));
                waitContractProductPojo.setId(contractProductEntity.getId());
                waitContractProductPojo.setContractPorudctId(contractProductEntity.getId());
                waitContractProductPojo.setProductId(productId);
                waitContractProductPojo.setProductName(productData.getString(ProductEnum.NAME.getAttr()));
                waitContractProductPojo.setProductNo(contractProductEntity.getProductNo());
                waitContractProductPojo.setNum(shortageQuantity);
                waitContractProductPojo.setProductNum(shortageQuantity);
                waitContractProductPojo.setProductThumnail(productData.getString(ProductEnum.PRODUCT_IMGS.getAttr()) == null ? new JSONArray() : productData.getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr()));
                String unit = contractProductEntity.getProductUnit();
                waitContractProductPojo.setProductUnit(unitItemMap.getOrDefault(unit, Objects.nonNull(unit) && (!ItemUtil.isUUID(unit) || !RegexUtil.isOnePositiveInt(unit.toString())) ? unit : ""));
                if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                    Long productUnit = productData.getLong(ProductEnum.UNIT.getAttr());
                    waitContractProductPojo.setTransformUnitRate(groupItemsMap.get(productUnit));
                    waitContractProductPojo.setEnableMultiUnit(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
                    if (!StringUtil.isDigital(unit) || Long.parseLong(unit) < ProductConstant.MAX_SINGLE_UNIT_VALUE) {
                        MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(productUnit);
                        if (Objects.nonNull(multiUnitItemPoJo)) {
                            waitContractProductPojo.setProductUnit(multiUnitItemPoJo.getBaseName());
                        }
                    }
                }
                waitContractProductPojo.setProductSpec(specificationModel.joinSpecification(productData.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr())));
                waitContractProductPojoList.add(waitContractProductPojo);
            }
            waitContractProduceMap.put(contractId, waitContractProductPojoList);
        }
        return waitContractProduceMap;
    }


    /**
     * 待采购缺货产品
     * @param corpid
     * @param cidList:用来存储满足缺货的合同ID 当长度大于pagesize时 可以点击下一页
     * @return
     * @throws XbbException
     */
    public LinkedHashMap<Long,List<WaitContractProductPojo>> getNewWaitContractProductPojoMap(LinkedHashMap<Long, List<WaitContractProductPojo>> waitContractProduceMap,FormDataListDTO formDataListDTO,String corpid,List<Long> cidList) throws XbbException {

        // 列表分页条数
        int listPageSize = 20;
        if (Objects.nonNull(formDataListDTO.getPageSize())){
            listPageSize = formDataListDTO.getPageSize();
        }

        // 自己分页查询 每次查询出500条
        int page = 0;
        int pageSize = 300;
        formDataListDTO.setPage(page +1);
        formDataListDTO.setSearchPageSize(pageSize);
        // 查询es数据
        XbbAggregatedPage waitPurchaseContract = getWaitPurchaseContract(formDataListDTO);


        // 不够时是否继续往下查询
        boolean isGo = true;
        List<Long> dataIdList = new ArrayList<>();
        List<PaasFormDataEntityExt> content = waitPurchaseContract.getContent();
        // 找到此次查询的最小的updatetime 如果查出来的500条不够拼凑20条有效数据时 下次从这个往下查询
        if (CollectionsUtil.isNotEmpty(content)) {
            for (PaasFormDataEntityExt paasFormDataEntityExt : content) {
                dataIdList.add(paasFormDataEntityExt.getId());
                Long updateTime = paasFormDataEntityExt.getUpdateTime();
                if (Objects.isNull(formDataListDTO.getLastUpdateTime()) || updateTime < formDataListDTO.getLastUpdateTime()){
                    formDataListDTO.setLastUpdateTime(updateTime);
                }
            }
            if(content.size() < 500){
                isGo = false;
            }
        }else {
            return waitContractProduceMap;
        }


        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid", corpid);
        map.put("del", 0);
        map.put("contractIdIn", dataIdList);
        // 合同状态在待系列正常
        map.put("status", 0);
        map.put("isProduce",0);
        //获取合同产品信息
        List<ContractProductEntity> contractProductEntityList = contractProductModel.findEntitys(map);
        // 关联产品按关联产品id升序排序
        contractProductEntityList.sort((o1, o2) -> (int)(o2.getId() - o1.getId()));
        Map<Long, List<ContractProductEntity>> contractProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, PaasFormDataEntityExt> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Long> productIdSet = new HashSet<>();
        List<String> onlyKeyList = new ArrayList<>();
        // 封装每个合同的更新时间map
        Map<Long,Long> contractUpdateTimeMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("columns","id,update_time");
        param.put("corpid", corpid);
        param.put("del", 0);
        param.put("idIn", dataIdList);
        List<ContractEntityExt> entitys = contractDao.findEntitys(param);
        if (CollectionsUtil.isNotEmpty(entitys)){
            entitys.forEach(item -> contractUpdateTimeMap.put(item.getId(),item.getUpdateTime()));
        }
        for (ContractProductEntity entity : contractProductEntityList) {
            if (Objects.equals(entity.getProductNum(),entity.getOutstockNum())){
                continue;
            }
            List<ContractProductEntity> singleContractProductList = new ArrayList<>();
            singleContractProductList.add(entity);
            productIdSet.add(entity.getProductId());
            if (contractProductMap.containsKey(entity.getContractId())) {
                singleContractProductList.addAll(contractProductMap.get(entity.getContractId()));
            }
            contractProductMap.put(entity.getContractId(), singleContractProductList);
            onlyKeyList.add(entity.getId() + "_" + entity.getProductId());
        }
        if (productIdSet.isEmpty()) {
            productIdSet.add(-1L);
        }
        // 获取该批合同下所有采购数量
        Map<String, Double> purchaseByContractMap = getPurchaseByContract(corpid, dataIdList);
        // 获取采购结存表所有数据
        List<PurchaseBalanceEntity> purchaseBalanceEntityList = new ArrayList<>();
        if (CollectionsUtil.isNotEmpty(onlyKeyList)){
            purchaseBalanceEntityList = purchaseBalanceModel.findByOnlyKeys(corpid, onlyKeyList);
        }
        // 超发库存map key = contractid_productid  value=超发库存总量
        Map<String, Double> exceedStockMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (CollectionsUtil.isNotEmpty(purchaseBalanceEntityList)){
            purchaseBalanceEntityList.forEach(item -> exceedStockMap.put(item.getOnlyKey(),item.getExceedStockNum()));
        }

        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(), productIdSet));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        // 限制返回值
        List<String> fieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias(), StringConstant.JSON_DATA, "formId");
        //关联产品的具体信息
        List<PaasFormDataEntityExt> paasFormDataEntityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
        for (PaasFormDataEntityExt entity : paasFormDataEntityExtList) {
            productMap.put(entity.getDataId(), entity);
        }
        Map<String, String> unitItemMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<UnitItemPoJo>> groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
        Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
        List<ItemPoJo> productItems = relativeProductHelp.getBusinessUnitItems(corpid);
        productItems.forEach(item -> {
            if (!Objects.equals(item.getIsOther(), 1)) {
                unitItemMap.put(item.getValue().toString(), item.getText());
            }
        });
        LinkedHashMap<Long, List<ContractProductEntity>> contractLinkHashMap = new LinkedHashMap<>();
        content.forEach(item ->{
            Long contractId = item.getId();
            List<ContractProductEntity> contractproductList = contractProductMap.getOrDefault(contractId, new ArrayList<>());
            contractLinkHashMap.put(contractId,contractproductList);
        });
        int accuary = 6;
        // 是否最后一页 1是 0不是
        Integer isLast = 1;
        for (Map.Entry<Long, List<ContractProductEntity>> entry : contractLinkHashMap.entrySet()) {
            List<ContractProductEntity> productEntityList = entry.getValue();
            Long contractId = entry.getKey();
            List<WaitContractProductPojo> waitContractProductPojoList = waitContractProduceMap.getOrDefault(contractId, new ArrayList<>());
            for (ContractProductEntity contractProductEntity : productEntityList) {
                Long productId = contractProductEntity.getProductId();
                Long contractProductId = contractProductEntity.getId();
                if (!productMap.containsKey(productId)) {
                    continue;
                }
                JSONObject productData = productMap.get(productId).getData();
//                double stock = Objects.isNull(productData.getDouble(ProductEnum.STOCK.getAttr())) ? 0D : productData.getDouble(ProductEnum.STOCK.getAttr());
                // 库存 + 已出库 - 合同数量 > 0 说明不需要采购
//                double shortageQuantity = Arith.sub(Arith.add(contractProductEntity.getOutstockNum() ,stock),contractProductEntity.getProductNum());
//                if (shortageQuantity > 0) {
//                    continue;
//                }
                // 新公式: 合同总量 - 采购总量 - 超发库存总量
                //采购总量
                String onlyKey = contractProductId + "_" +productId;
                double purchaseSumNum = 0D;
                if(!purchaseByContractMap.isEmpty() && purchaseByContractMap.containsKey(onlyKey)){
                    purchaseSumNum = purchaseByContractMap.get(contractProductId + "_" + productId);
                }
                // 超发库存总量
                double exceedNum = 0D;
                if (!exceedStockMap.isEmpty() && exceedStockMap.containsKey(onlyKey)){
                    exceedNum = exceedStockMap.get(onlyKey);
                }
                double shortageQuantity = Arith.sub(contractProductEntity.getProductNum(),Arith.add(purchaseSumNum,exceedNum));
                if (shortageQuantity <= 0){
                    continue;
                }
                double waitPurchase = contractProductEntity.getProductNum();
                WaitContractProductPojo waitContractProductPojo = new WaitContractProductPojo();
//                if (Objects.nonNull(contractProductEntity.getBusinessUnit())) {
//                    List<UnitItemPoJo> unitItemPoJos = groupItemsMap.get(contractProductEntity.getGroupId());
//                    if (CollectionsUtil.isNotEmpty(unitItemPoJos)) {
//                        accuary = unitItemPoJos.get(0).getAccuracy();
//                    }
//                    contractProductEntity.setProductUnit(contractProductEntity.getBusinessUnit().toString());
//                    shortageQuantity = Arith.div(shortageQuantity, contractProductEntity.getRate(), accuary);
//                }
                waitContractProductPojo.setParentId(productData.getLong(ProductEnum.PARENT_ID.getAttr()));
                waitContractProductPojo.setId(productId);
                waitContractProductPojo.setProductId(productId);
                waitContractProductPojo.setProductName(productData.getString(ProductEnum.NAME.getAttr()));
                waitContractProductPojo.setProductNo(contractProductEntity.getProductNo());
                waitContractProductPojo.setNum(shortageQuantity);
                waitContractProductPojo.setProductNum(shortageQuantity);
                waitContractProductPojo.setProductThumnail(productData.getString(ProductEnum.PRODUCT_IMGS.getAttr()) == null ? new JSONArray() : productData.getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr()));
                String unit = contractProductEntity.getProductUnit();
                waitContractProductPojo.setProductUnit(unitItemMap.getOrDefault(unit, Objects.nonNull(unit) && (!ItemUtil.isUUID(unit) || !RegexUtil.isOnePositiveInt(unit.toString())) ? unit : ""));
                if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                    Long productUnit = productData.getLong(ProductEnum.UNIT.getAttr());
                    waitContractProductPojo.setTransformUnitRate(groupItemsMap.get(productUnit));
                    waitContractProductPojo.setEnableMultiUnit(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
                    if (!StringUtil.isDigital(unit) || Long.parseLong(unit) < ProductConstant.MAX_SINGLE_UNIT_VALUE) {
                        MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(productUnit);
                        if (Objects.nonNull(multiUnitItemPoJo)) {
                            waitContractProductPojo.setProductUnit(multiUnitItemPoJo.getBaseName());
                        }
                    }
                }
                waitContractProductPojo.setProductSpec(specificationModel.joinSpecification(productData.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr())));
                waitContractProductPojoList.add(waitContractProductPojo);
            }
            if (CollectionsUtil.isNotEmpty(waitContractProductPojoList)){
                cidList.add(contractId);
            }
            if (CollectionsUtil.isNotEmpty(waitContractProductPojoList) && waitContractProduceMap.size() < listPageSize){
                waitContractProduceMap.put(contractId, waitContractProductPojoList);
                Long updateTime = contractUpdateTimeMap.getOrDefault(contractId,0L);
                if (Objects.isNull(formDataListDTO.getLastTime()) || updateTime < formDataListDTO.getLastTime()){
                    formDataListDTO.setLastTime(updateTime);
                }
                if (Objects.isNull(formDataListDTO.getFirstTime()) || updateTime > formDataListDTO.getFirstTime()){
                    formDataListDTO.setFirstTime(updateTime);
                }
            }
            if (cidList.size() > listPageSize){
                isLast = 0;
                break;
            }
        }
        formDataListDTO.setIsLast(isLast);
        // 假如查询出来的数据已经够分页条数了 则继续查询的条数变小一点增加查询效率
        if (listPageSize == cidList.size() && isGo){
            formDataListDTO.setSearchPageSize(100);
        }
        // 当符合缺货数量少于分页数量 或者下一页标识没拿到的时候  且查询的下一页数据还有的时候
        if ((waitContractProduceMap.size() < listPageSize  || cidList.size() < listPageSize) && isGo){
            getNewWaitContractProductPojoMap(waitContractProduceMap,formDataListDTO,corpid,cidList);
        }
        return waitContractProduceMap;
    }

    /**
     * @Author: wujian
     * @Description: 根据合同id获取该合同下的采购总量
     * @Date: 下午2:59 2021/9/13
     * @Param: [corpid, contractIdList]
     * @return: java.util.Map<java.lang.String,java.lang.Double>
     **/
    public Map<String, Double> getPurchaseByContract(String corpid , List<Long> contractIdList){
        List<PurchaseProductEntity> purchaseProductEntities = purchaseProductModel.getPurchaseByContract(corpid, contractIdList);
        // contractProductId_productId 该合同产品的采购总量
        Map<String, Double> purchaseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (CollectionsUtil.isNotEmpty(purchaseProductEntities)){
            for (PurchaseProductEntity entity : purchaseProductEntities) {
                if (!purchaseMap.containsKey(entity.getContractProductId() + "_" + entity.getProductId())){
                    purchaseMap.put(entity.getContractProductId() + "_" + entity.getProductId(), entity.getProductNum());
                }else {
                    // 如果包含了说明采购多个 num+=num
                    BigDecimal b1 = new BigDecimal(Double.toString(purchaseMap.get(entity.getContractProductId() + "_" + entity.getProductId())));
                    BigDecimal b2 = new BigDecimal(Double.toString(entity.getProductNum()));
                    purchaseMap.put(entity.getContractProductId() + "_" + entity.getProductId(),  b1.add(b2).doubleValue());
                }
            }
        }
        return  purchaseMap;
    }

    /**
     * @Author: wujian
     * @Description: 根据合同id获取该合同下所有采购合同供应商及已入库数量
     * @Date: 下午2:59 2021/9/13
     * @Param: [corpid, contractIdList]
     * @return: java.util.Map<java.lang.String,java.lang.Double>
     **/
    public List<WaitPurchasePojo> getPurchaseSupplierByContract(String corpid , List<Long> contractIdList) throws XbbException {
        List<WaitPurchasePojo> waitPurchasePojoList = new ArrayList<>();
        List<PurchaseProductEntity> purchaseProductEntities = purchaseProductModel.getPurchaseByContract(corpid, contractIdList);
        Long contractId = 0L;
        if(CollectionsUtil.isNotEmpty(contractIdList)){
            contractId = contractIdList.get(0);
        }
        // contractId_productId 该合同产品的采购总量
        Map<String, Double> purchaseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        Set<Long> purchaseIdSet = new HashSet<>();
        // key=productid  value=purchaseId
        Map<Long, Long> productPurchaseIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // key=purchaseId value=supplieridlsit
        Map<Long,String> purchaseSupplierMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<String> supplierIdSet = new HashSet<>() ;
        if (CollectionsUtil.isNotEmpty(purchaseProductEntities)){
            for (PurchaseProductEntity entity : purchaseProductEntities) {
                purchaseIdSet.add(entity.getPurchaseSheetId());
            }
//            // 查询出所有采购合同做采购合同及供应商关联map
//            List<PurchaseEntityExt> purchaseList = purchaseModel.getPurchaseListByIdIn(corpid, new ArrayList(purchaseIdSet));
//            // 循环查询出来的所有采购合同取采购合同和供应商对应关系
//            for (PurchaseEntityExt purchaseEntityExt : purchaseList) {
//                JSONObject data = purchaseEntityExt.getData();
//                String supplierId = saasUpdateHelp.getStringOrDefaultFromFormData(data, PurchaseEnum.SUPPLIER_ID.getAttr(), "0");
//                purchaseSupplierMap.put(purchaseEntityExt.getId(), supplierId);
//            }
            for (PurchaseProductEntity entity : purchaseProductEntities) {
                WaitPurchasePojo waitPurchasePojo = new WaitPurchasePojo();
                String onlyKey = entity.getContractProductId() + "_" + entity.getProductId();
                waitPurchasePojo.setOnlyKey(onlyKey);

                productPurchaseIdMap.put(entity.getProductId(),entity.getPurchaseSheetId());
                if (purchaseMap.containsKey(onlyKey)){
                    purchaseMap.put(onlyKey,Arith.add(purchaseMap.get(entity.getContractProductId() + "_" + entity.getProductId()),entity.getInstockNum()));
                    waitPurchasePojoList.forEach(item ->{
                        if (Objects.equals(item.getOnlyKey(),onlyKey)){
                            item.setPurchaseInstockNum(Arith.add(item.getPurchaseInstockNum(),entity.getInstockNum()));
//                            Set<String> supIdSet = item.getSupplierIdSet();
//                            supIdSet.add(purchaseSupplierMap.get(entity.getPurchaseSheetId()));
//                            item.setSupplierIdSet(supIdSet);
                        }
                    });
                }else {
                    waitPurchasePojo.setPurchaseInstockNum(entity.getInstockNum());
//                    Set<String> supIdSet = new HashSet<>();
//                    supIdSet.add(purchaseSupplierMap.get(entity.getPurchaseSheetId()));
//                    waitPurchasePojo.setSupplierIdSet(supIdSet);
                    purchaseMap.put(entity.getContractProductId() + "_" + entity.getProductId(),entity.getInstockNum());
                    waitPurchasePojoList.add(waitPurchasePojo);
                }

            }

        }
        return  waitPurchasePojoList;
    }

    /**
     * 待采购待生产获取缺货合同
     * @param corpid
     * @param dataIdList
     * @param lackStockMap
     * @param isProduce
     * @return
     * @throws XbbException
     */
    public Map<Long,WaitContractPojo> getWaitContractPojoMap(String corpid, List<Long> dataIdList, Map<Long, Double> lackStockMap, Integer isProduce,Map<Long,List<Long>> productAndContractIdMap,Map<Long,Double> stockMap) throws XbbException {
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid", corpid);
        map.put("productIdIn", dataIdList);
        map.put("isProduce", isProduce);
        map.put("del", 0);
        //合同关联产品
        List<ContractProductEntity> contractProductEntityList = contractProductModel.findEntitys(map);
        Set<Long> contractIdSet = new HashSet<>();
        for (ContractProductEntity contractProductEntity : contractProductEntityList) {
            contractIdSet.add(contractProductEntity.getContractId());
        }
        if (contractIdSet.isEmpty()) {
            return new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(), contractIdSet));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ARCHIVED), ArchivedEnum.ARCHIVED.getCode()));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(),Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
        // 限制返回值
        List<String> fieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias(), FieldTypeEnum.SERIALNO.getAlias(), ContractEnum.NAME.getAttr(), ContractEnum.LINK_CUSTOMER_HIDE.getAttr(), ContractEnum.SHIP_STATUS.getAttr());
//        List<PaasFormDataEntityExt> paasFormDataEntityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTRACT,boolQueryBuilder,PaasFormDataEntityExt.class,fieldList);
        SearchRequest searchRequest = EsUtil.simplePackageForQueryForPage(IndexTypeEnum.IDX_SAAS_CONTRACT,boolQueryBuilder,fieldList,0, contractIdSet.size());
        XbbAggregatedPage<PaasFormDataEntityExt> result =  xbbElasticsearchRestTemplate.queryForPages(searchRequest,PaasFormDataEntityExt.class);
        List<PaasFormDataEntityExt> paasFormDataEntityExtList = result.getContent();
        List<Long> archivedIds = new ArrayList<>();
        paasFormDataEntityExtList.forEach(item->archivedIds.add(item.getDataId()));

        List<Long> closedProductContractList = new ArrayList<>();
        for (PaasFormDataEntityExt entityExt : paasFormDataEntityExtList) {
            JSONObject data = entityExt.getData();
            String shipStatus = FastJsonHelper.getStringOrDefaultFromFormData(data, ContractEnum.SHIP_STATUS.getAttr(), ShipStatusEnum.UNSHIPPED.getCode());
            if (!Objects.equals(shipStatus, ShipStatusEnum.SHIPPED.getCode()) && Objects.equals(shipStatus, ShipStatusEnum.CLOSED.getCode())) {
                closedProductContractList.add(entityExt.getId());
            }
        }
        Map<String,Double> contractProudctNumMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (ContractProductEntity entity : contractProductEntityList) {
            if (!archivedIds.contains(entity.getContractId())) {
                continue;
            }
            if (Objects.equals(entity.getProductNum(),entity.getOutstockNum())){
                continue;
            }
            if (closedProductContractList.contains(entity.getContractId())){
                continue;
            }
            String key = entity.getContractId() + "_" + entity.getProductId();
            Double num = entity.getProductNum() - entity.getOutstockNum();
            Double lackNum = contractProudctNumMap.getOrDefault(key,0D);
            lackNum += num;
            contractProudctNumMap.put(key,lackNum);
        }
        Set<Long> realContractIdSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (Map.Entry<String,Double> entry : contractProudctNumMap.entrySet()){
            String[] keyList = entry.getKey().split("_");
            Long contractId = Long.valueOf(keyList[0]);
            Long productId = Long.valueOf(keyList[1]);
            Double productStock = stockMap.getOrDefault(productId,0D);
            productStock = Objects.isNull(productStock) ? 0D : productStock;
            if (productStock < entry.getValue()){
                realContractIdSet.add(contractId);
                List<Long> contractIdList = productAndContractIdMap.getOrDefault(productId, new ArrayList<>());
                contractIdList.add(contractId);
                productAndContractIdMap.put(productId, contractIdList);
                if (lackStockMap.containsKey(productId)){
                    Double lackStock = lackStockMap.get(productId);
                    lackStock += entry.getValue();
                    lackStockMap.put(productId, lackStock);
                }else {
                    lackStockMap.put(productId, entry.getValue() - productStock);
                }
            }
        }
        if (realContractIdSet.isEmpty()) {
            return new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        }
        paasFormDataEntityExtList.removeIf(item-> !realContractIdSet.contains(item.getDataId()));
        Map<Long,WaitContractPojo> waitContractPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasFormDataEntityExt entity : paasFormDataEntityExtList) {
            WaitContractPojo waitContractPojo = new WaitContractPojo();
            JSONObject contractData = entity.getData();
            waitContractPojo.setId(entity.getDataId());
            waitContractPojo.setContractId(entity.getDataId());
            waitContractPojo.setContractName(contractData.getString(ContractEnum.NAME.getAttr()));
            waitContractPojo.setContractNo(entity.getSerialNo());
            waitContractPojo.setCustomerName(contractData.getString(ContractEnum.LINK_CUSTOMER_HIDE.getAttr()));
            waitContractPojoMap.put(entity.getDataId(), waitContractPojo);
        }
        return waitContractPojoMap;
    }

    public void handleCategory(FormDataListDTO formDataListDTO, PaasFormDataEsListVO formDataListVO) throws XbbException{
        if (Objects.equals(formDataListDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode())) {
            Map<Long, String> categoryMap = productListHelp.categoryList(formDataListDTO.getCorpid());
            for (PaasFormDataEntityExt paasFormDataEntityExt : formDataListVO.getPaasFormDataESList()) {
                paasFormDataEntityExt.getData().put(ProductEnum.CATEGORY_ID.getAttr(), categoryMap.getOrDefault(FastJsonHelper.getLongOrDefaultFromFormData(paasFormDataEntityExt.getData(), ProductEnum.CATEGORY_ID.getAttr(), 0L), ""));
            }
        }
    }

    /**
     * 过滤子表单
     * @param formDataListVO
     * @param explainMap
     */
    public void filterSubForm(PaasFormDataEsListVO formDataListVO, Map<String,FieldAttrEntity> explainMap) {
        List<String> subFormAttrList = new ArrayList<>();
        for (Map.Entry<String,FieldAttrEntity> entry : explainMap.entrySet()){
            FieldAttrEntity entity = entry.getValue();
            if (Objects.equals(FieldTypeEnum.SUB_FORM.getType(),entity.getFieldType()) || Objects.equals(FieldTypeEnum.CONTACT_NUMBER.getType(),entity.getFieldType())){
                subFormAttrList.add(entity.getAttr());
            }
        }
        for (PaasFormDataEntityExt entityExt : formDataListVO.getPaasFormDataESList()){
            JSONObject data = entityExt.getData();
            for (String attr : subFormAttrList){
                if (data.containsKey(attr)){
                    JSONArray jsonArray = data.getJSONArray(attr);
                    if (Objects.nonNull(jsonArray) && jsonArray.size() > 3){
                        data.put(attr,Arrays.asList(jsonArray.get(0),jsonArray.get(1)));
                    }
                }
            }
        }
    }

    /**
     * 获取单据关联产品总数
     * @param dataId 单据id
     * @param businessType 业务类型
     * @param corpid 公司id
     * @param type 装配单产品类型，仅装配单
     * @return 总数
     */
    public Integer getRefProductListTotal(Long dataId, Integer businessType, String corpid, int type) {
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        switch (xbbRefTypeEnum) {
            case CONTRACT:
            case ORDER:
                map.put("contractId",dataId);
                map.put("type",XbbRefTypeEnum.CONTRACT.getCode());
                return contractProductModel.getEntitysCount(map);
            case SALES_OPPORTUNITY:
                map.put("opportunityId",dataId);
                return opportunityProductModel.getEntitysCount(map);
            case PURCHASE:
                map.put("purchaseSheetId",dataId);
                return purchaseProductModel.getEntitysCount(map);
            case RETURNED_PURCHASE:
                map.put("returnPurchaseId",dataId);
                return returnedPurchaseProductModel.getEntitysCount(map);
            case ASSEMBLE:
                map.put("assembleId",dataId);
                map.put("type",type);
                return assembleProductModel.getEntitysCount(map);
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
                map.put("intoWarehouseId",dataId);
                return instockProductModel.getEntitysCount(map);
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case ORDER_OUTSTOCK:
                map.put("outWarehouseId",dataId);
                return outstockProductModel.getEntitysCount(map);
            case INVENTORY:
                map.put("inventoryId",dataId);
                return inventoryProductModel.getEntitysCount(map);
            case TRANSFER:
                map.put("transferId",dataId);
                return transferProductModel.getEntitysCount(map);
            case REFUND:
            case RETURN:
                map.put("contractId", dataId);
                map.put("type",XbbRefTypeEnum.REFUND.getCode());
                return contractProductModel.getEntitysCount(map);
            case WORK_ORDER:
                map.put("workOrderId", dataId);
                return workOrderProductModel.getEntitysCount(map);
            case QUOTATION:
                map.put("quotationId", dataId);
                return quotationProductModel.getEntitysCount(map);
            case BOM_BILL:
                map.put("bomId",dataId);
                map.put("type",type);
                return bomProductModel.getEntitysCount(map);
            case PRODUCTION_ORDER:
                map.put("productionOrderId",dataId);
                map.put("type",type);
                return productionOrderProductModel.getEntitysCount(map);
            case CUSTOMER_STATEMENT:
                map.put("statementId", dataId);
                map.put("snapshot", 0);
                return customerStatementProductModel.getEntitysCount(map);
            case CUSTOMER_STATEMENT_SNAPSHOT:
                map.put("statementId", dataId);
                map.put("snapshot", 1);
                return customerStatementProductModel.getEntitysCount(map);
            case PROMOTION_ACTIVITY_MANAGEMENT:
                map.put("refId",dataId);
                return promotionProductModel.getEntityCount(map);
            default:
                return 0;
        }
    }

    /**
     * 快速取解释
     * @param businessType
     * @param corpid
     * @return
     */
    public Map<String, FieldAttrEntity> getExplains(Integer businessType,String corpid) throws XbbException{
        PaasFormExplainEntity formExplain = paasFormExplainModel.getByBusinessType(businessType,corpid);
        Map<String, FieldAttrEntity> explainMap= null;
        if(Objects.nonNull(formExplain)) {
            String explains = formExplain.getExplains();
            if(explains!=null){
                explainMap = ExplainUtil.getExplainMap(explains, null);
            }
        }
        return explainMap;
    }

    /**
     * 编辑页获取金额明细
     * @param invoiceRelationshipEntityList
     * @return
     */
    public JSONArray getMoneyDetail(List<InvoiceRelationshipEntity> invoiceRelationshipEntityList,JSONObject result,Long invoiceId,String corpid,Integer fromRed,Integer isEdit,Integer isRed) throws XbbException{
        JSONArray amountDetail = new JSONArray();
        List<Long> contractIdList = new ArrayList<>();
        List<Long> paymentIdList = new ArrayList<>();
        List<Long> paymentSheetIdList = new ArrayList<>();
        Map<Long, RelationshipGetPojo> refInvoiceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,Object> contractMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,Object> paymentOrPaymentSheetMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,Double> contractInvoiceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,Double> paymentOrPaymentSheetInvoiceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, InvoiceRelationshipEntity> refRelationshipPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        boolean isHasRed = false;
        boolean isfromRed = Objects.equals(fromRed,BasicConstant.ONE);
        if(Objects.nonNull(result)){
            if(Objects.equals(getIntegerOrDefaultFromFormData(result,InvoiceEnum.HAS_RED.getAttr(),BasicConstant.ZERO),BasicConstant.ONE)){
                isHasRed = true;
            }
        }
        boolean moreRed = isfromRed && isHasRed;
        if(CollectionsUtil.isNotEmpty(invoiceRelationshipEntityList)){
            for(InvoiceRelationshipEntity invoiceRelationshipEntity : invoiceRelationshipEntityList){
                RelationshipGetPojo relationshipGetPojo = new RelationshipGetPojo();
                relationshipGetPojo.setContractId(invoiceRelationshipEntity.getContractId());
                relationshipGetPojo.setContractNo(invoiceRelationshipEntity.getContractNo());
                relationshipGetPojo.setPaymentId(invoiceRelationshipEntity.getPaymentId());
                relationshipGetPojo.setPaymentNo(invoiceRelationshipEntity.getPaymentNo());
                relationshipGetPojo.setPaymentSheetId(invoiceRelationshipEntity.getPaymentSheetId());
                relationshipGetPojo.setPaymentSheetNo(invoiceRelationshipEntity.getPaymentSheetNo());
                if(Objects.equals(fromRed,BasicConstant.ONE) || Objects.equals(isRed,BasicConstant.ONE)){
                    relationshipGetPojo.setIsRed(BasicConstant.ONE);
                }else {
                    relationshipGetPojo.setIsRed(BasicConstant.ZERO);
                }
                amountDetail.add(relationshipGetPojo);
                boolean isRefContract = Objects.nonNull(invoiceRelationshipEntity.getContractId()) || Objects.equals(invoiceRelationshipEntity.getContractId(),0L);
                if(isRefContract && Objects.equals(invoiceRelationshipEntity.getPaymentId().intValue(),BasicConstant.ZERO) && Objects.equals(invoiceRelationshipEntity.getPaymentSheetId().intValue(),BasicConstant.ZERO)){
                    contractIdList.add(invoiceRelationshipEntity.getContractId());
                    refInvoiceMap.put(invoiceRelationshipEntity.getContractId(),relationshipGetPojo);
                    refRelationshipPojoMap.put(invoiceRelationshipEntity.getContractId(),invoiceRelationshipEntity);
                    getEditInvoiceAmount(RefTypeEnum.CONTRACT,relationshipGetPojo,invoiceRelationshipEntity.getMoney(),fromRed);
                }else if(Objects.nonNull(invoiceRelationshipEntity.getPaymentId()) && Objects.equals(invoiceRelationshipEntity.getPaymentSheetId().intValue(),BasicConstant.ZERO) && Objects.nonNull(invoiceRelationshipEntity.getContractId())){
                    contractIdList.add(invoiceRelationshipEntity.getContractId());
                    paymentIdList.add(invoiceRelationshipEntity.getPaymentId());
                    refInvoiceMap.put(invoiceRelationshipEntity.getPaymentId(),relationshipGetPojo);
                    refRelationshipPojoMap.put(invoiceRelationshipEntity.getPaymentId(),invoiceRelationshipEntity);
                    getEditInvoiceAmount(RefTypeEnum.PAYMENT,relationshipGetPojo,invoiceRelationshipEntity.getMoney(),fromRed);
                }else if(Objects.nonNull(invoiceRelationshipEntity.getPaymentSheetId()) && Objects.equals(invoiceRelationshipEntity.getPaymentId().intValue(),BasicConstant.ZERO) && Objects.nonNull(invoiceRelationshipEntity.getContractId())){
                    contractIdList.add(invoiceRelationshipEntity.getContractId());
                    paymentSheetIdList.add(invoiceRelationshipEntity.getPaymentSheetId());
                    refInvoiceMap.put(invoiceRelationshipEntity.getPaymentSheetId(),relationshipGetPojo);
                    refRelationshipPojoMap.put(invoiceRelationshipEntity.getPaymentSheetId(),invoiceRelationshipEntity);
                    getEditInvoiceAmount(RefTypeEnum.PAYMENTSHEET,relationshipGetPojo,invoiceRelationshipEntity.getMoney(),fromRed);
                }
            }
            Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<ContractEntityExt> contractEntityExtList = new ArrayList<>();
            map.put("del",DelEnum.NORMAL.getDel());
            if(CollectionsUtil.isNotEmpty(contractIdList)){
                map.put(BasicConstant.IDIN,contractIdList);
                contractEntityExtList = contractModel.findEntitys(map);
                /*if(Objects.equals(fromRed,BasicConstant.ONE) || Objects.equals(isEdit,BasicConstant.ONE)) {
                    if (CollectionsUtil.isEmpty(contractEntityExtList)) {
                        throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_216044);
                    }
                }*/
            }
            if(CollectionsUtil.isNotEmpty(contractIdList) && CollectionsUtil.isEmpty(paymentIdList) && CollectionsUtil.isEmpty(paymentSheetIdList)){
                getRefEntityExt(invoiceId,corpid,refRelationshipPojoMap,new ArrayList<>(contractEntityExtList),refInvoiceMap,contractMap,isRed,isEdit,fromRed,moreRed);
                if(Objects.nonNull(result)) {
                    //只有编辑页才需要跟改result
                    getRelationEntityToDisplay(result, RefTypeEnum.CONTRACT, contractMap,contractInvoiceMap,false);
                }
            }
            if(CollectionsUtil.isNotEmpty(paymentIdList) && CollectionsUtil.isNotEmpty(contractIdList) && CollectionsUtil.isEmpty(paymentSheetIdList)){
                map.put(BasicConstant.IDIN,paymentIdList);
                List<PaymentEntityExt> paymentEntityExtList = paymentModel.findEntitys(map);
                /*if(Objects.equals(fromRed,BasicConstant.ONE) || Objects.equals(isEdit,BasicConstant.ONE)) {
                    if (CollectionsUtil.isEmpty(paymentEntityExtList)) {
                        throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_216045);
                    }
                }*/
                getRefEntityExt(invoiceId,corpid,null,new ArrayList<>(contractEntityExtList),null,contractMap,isRed,isEdit,fromRed,false);
                getRefEntityExt(invoiceId,corpid,refRelationshipPojoMap,new ArrayList<>(paymentEntityExtList),refInvoiceMap,paymentOrPaymentSheetMap,isRed,isEdit,fromRed,moreRed);
                if(Objects.nonNull(result)) {
                    getRelationEntityToDisplay(result, RefTypeEnum.CONTRACT, contractMap,contractInvoiceMap,false);
                    getRelationEntityToDisplay(result, RefTypeEnum.PAYMENT, paymentOrPaymentSheetMap,paymentOrPaymentSheetInvoiceMap,false);
                }
            }else if(CollectionsUtil.isNotEmpty(paymentSheetIdList)  && CollectionsUtil.isEmpty(paymentIdList)){
                map.put(BasicConstant.IDIN,paymentSheetIdList);
                List<PaymentSheetEntityExt> paymentSheetEntityExtList = paymentSheetModel.findEntitys(map);
                /*if(Objects.equals(fromRed,BasicConstant.ONE) || Objects.equals(isEdit,BasicConstant.ONE)) {
                    if (CollectionsUtil.isEmpty(paymentSheetEntityExtList)) {
                        throw new XbbException(ErrorCodeEnum.API_ERROR_216046);
                    }
                }*/
                getRefEntityExt(invoiceId,corpid,null,new ArrayList<>(contractEntityExtList),null,contractMap,isRed,isEdit,fromRed,false);
                getRefEntityExt(invoiceId,corpid,refRelationshipPojoMap,new ArrayList<>(paymentSheetEntityExtList),refInvoiceMap,paymentOrPaymentSheetMap,isRed,isEdit,fromRed,moreRed);
                if(Objects.nonNull(result)) {
                    boolean isPrePaymentSheet = false;
                    if(CollectionsUtil.isNotEmpty(contractIdList)) {
                        for(Long contract: contractIdList){
                            if(Objects.equals(contract,0L)){
                                isPrePaymentSheet = true;
                            }
                        }
                        if(!isPrePaymentSheet) {
                            getRelationEntityToDisplay(result, RefTypeEnum.CONTRACT, contractMap, contractInvoiceMap,isPrePaymentSheet);
                        }
                    }
                    getRelationEntityToDisplay(result, RefTypeEnum.PAYMENTSHEET, paymentOrPaymentSheetMap,paymentOrPaymentSheetInvoiceMap,isPrePaymentSheet);
                }
            }
        }
        return amountDetail;
    }

    private void getRefEntityExt(Long invoiceId,String corpid,Map<Long, InvoiceRelationshipEntity> refRelationshipPojoMap,List<Object> entityExt,Map<Long, RelationshipGetPojo> refInvoiceMap,Map<Long,Object> refEntityMap,Integer isRed,Integer isEdit,Integer fromRed,boolean moreRed) throws XbbException{
        List<Long> idList= new ArrayList<>();
        if(CollectionsUtil.isNotEmpty(entityExt)) {
            for (Object object : entityExt) {
                if (object instanceof ContractEntityExt) {
                    ContractEntityExt contractEntityExt = (ContractEntityExt) object;
                    if(refEntityMap != null) {
                        refEntityMap.put(contractEntityExt.getId(), object);
                    }
                    if(refInvoiceMap != null) {
                        JSONObject contractData = contractEntityExt.getData();
                        RelationshipGetPojo relationshipGetPojo = refInvoiceMap.get(contractEntityExt.getId());
                        if(moreRed || Objects.equals(relationshipGetPojo.getIsRed(),BasicConstant.ONE) || (Objects.equals(isRed,BasicConstant.ONE) &&  Objects.equals(isEdit,BasicConstant.ONE))){
                            //新建红冲的时候走这里金额要置成负的,红冲发票 关系表中的金额本来就是负的编辑走下面的
                            if(Objects.equals(isRed,BasicConstant.ONE) &&  Objects.equals(isEdit,BasicConstant.ONE)){
                                //编辑红冲
                                Map<Long,Double> contractAmountMap = getOriginInvoiceAmount(invoiceId,corpid,RefTypeEnum.CONTRACT);
                                Double amount = 0D;
                                if(Objects.nonNull(contractAmountMap)){
                                    amount = contractAmountMap.get(contractEntityExt.getId());
                                }else {
                                    amount = contractData.getDouble(ContractEnum.AMOUNT.getAttr());
                                }
                                relationshipGetPojo.setContractAmount(-amount);
                            }else {
                                relationshipGetPojo.setContractAmount(-contractData.getDouble(ContractEnum.AMOUNT.getAttr()));
                            }
                        }else {
                            relationshipGetPojo.setContractAmount(contractData.getDouble(ContractEnum.AMOUNT.getAttr()));
                        }
                        //关联业务若只是组装就走上面
                        if(moreRed){
                            InvoiceRelationshipEntity invoiceRelationshipEntity = refRelationshipPojoMap.get(contractEntityExt.getId());
                            idList.add(contractEntityExt.getId());
                            Double invoiceAmount = historyInvoiceAmount(invoiceRelationshipEntity,RefTypeEnum.CONTRACT,invoiceId,corpid,idList,isEdit,moreRed);
                            getEditInvoiceAmount(RefTypeEnum.CONTRACT,relationshipGetPojo,invoiceAmount,fromRed);
                        }
                    }
                } else if (object instanceof PaymentEntityExt) {
                    PaymentEntityExt paymentEntityExt = (PaymentEntityExt) object;
                    if(refEntityMap != null) {
                        refEntityMap.put(paymentEntityExt.getId(), object);
                    }
                    if(refInvoiceMap != null) {
                        JSONObject paymentData = paymentEntityExt.getData();
                        RelationshipGetPojo relationshipGetPojo = refInvoiceMap.get(paymentEntityExt.getId());
                        if(moreRed || Objects.equals(relationshipGetPojo.getIsRed(),BasicConstant.ONE) || ( Objects.equals(isRed,BasicConstant.ONE) &&  Objects.equals(isEdit,BasicConstant.ONE))){
                            relationshipGetPojo.setPaymentAmount(-paymentData.getDouble(PaymentEnum.AMOUNT.getAttr()));
                            if(Objects.equals(isRed,BasicConstant.ONE) &&  Objects.equals(isEdit,BasicConstant.ONE)){
                                //编辑红冲
                                Map<Long,Double> paymentAmountMap = getOriginInvoiceAmount(invoiceId,corpid,RefTypeEnum.PAYMENT);
                                Double amount = 0D;
                                if(Objects.nonNull(paymentAmountMap)){
                                    amount = paymentAmountMap.get(paymentEntityExt.getId());
                                }else {
                                    amount = paymentData.getDouble(PaymentEnum.AMOUNT.getAttr());
                                }
                                relationshipGetPojo.setPaymentAmount(-amount);
                            }else {
                                relationshipGetPojo.setPaymentAmount(-paymentData.getDouble(PaymentEnum.AMOUNT.getAttr()));
                            }
                        }else {
                            relationshipGetPojo.setPaymentAmount(paymentData.getDouble(PaymentEnum.AMOUNT.getAttr()));
                        }
                        if(moreRed){
                            InvoiceRelationshipEntity invoiceRelationshipEntity = refRelationshipPojoMap.get(paymentEntityExt.getId());
                            idList.add(paymentEntityExt.getId());
                            Double invoiceAmount = historyInvoiceAmount(invoiceRelationshipEntity,RefTypeEnum.PAYMENT,invoiceId,corpid,idList,isEdit,moreRed);
                            getEditInvoiceAmount(RefTypeEnum.PAYMENT,relationshipGetPojo,invoiceAmount,fromRed);
                        }
                    }
                } else if (object instanceof PaymentSheetEntityExt) {
                    PaymentSheetEntityExt paymentSheetEntityExt = (PaymentSheetEntityExt) object;
                    if(refEntityMap != null) {
                        refEntityMap.put(paymentSheetEntityExt.getId(), object);
                    }
                    if(refInvoiceMap != null) {
                        JSONObject paymentSheetData = paymentSheetEntityExt.getData();
                        RelationshipGetPojo relationshipGetPojo = refInvoiceMap.get(paymentSheetEntityExt.getId());
                        if(moreRed || Objects.equals(relationshipGetPojo.getIsRed(),BasicConstant.ONE) || ( Objects.equals(isRed,BasicConstant.ONE) &&  Objects.equals(isEdit,BasicConstant.ONE))){
                            relationshipGetPojo.setPaymentSheetAmount(-paymentSheetData.getDouble(PaymentSheetEnum.AMOUNT.getAttr()));
                            if(Objects.equals(isRed,BasicConstant.ONE) &&  Objects.equals(isEdit,BasicConstant.ONE)){
                                //编辑红冲
                                Map<Long,Double> paymentSheetAmountMap = getOriginInvoiceAmount(invoiceId,corpid,RefTypeEnum.PAYMENTSHEET);
                                Double amount = 0D;
                                if(Objects.nonNull(paymentSheetAmountMap)){
                                    amount = paymentSheetAmountMap.get(paymentSheetEntityExt.getId());
                                }else {
                                    amount = paymentSheetData.getDouble(PaymentSheetEnum.AMOUNT.getAttr());
                                }
                                relationshipGetPojo.setPaymentSheetAmount(-amount);
                            }else {
                                relationshipGetPojo.setPaymentSheetAmount(-paymentSheetData.getDouble(PaymentSheetEnum.AMOUNT.getAttr()));
                            }
                        }else {
                            relationshipGetPojo.setPaymentSheetAmount(paymentSheetData.getDouble(PaymentSheetEnum.AMOUNT.getAttr()));
                        }
                        if(moreRed){
                            InvoiceRelationshipEntity invoiceRelationshipEntity = refRelationshipPojoMap.get(paymentSheetEntityExt.getId());
                            idList.add(paymentSheetEntityExt.getId());
                            Double invoiceAmount = historyInvoiceAmount(invoiceRelationshipEntity,RefTypeEnum.PAYMENTSHEET,invoiceId,corpid,idList,isEdit,moreRed);
                            getEditInvoiceAmount(RefTypeEnum.PAYMENTSHEET,relationshipGetPojo,invoiceAmount,fromRed);
                        }
                    }
                }
            }
        }
    }

    public Map<Long,Double> getOriginInvoiceAmount(Long invoiceId,String corpid,RefTypeEnum refTypeEnum){
        InvoiceEntityExt invoiceEntityExt = invoiceModel.getByKey(invoiceId,corpid);
        Long originId = 0L;
        if(Objects.nonNull(invoiceEntityExt)){
            originId = invoiceEntityExt.getData().getLong(InvoiceEnum.ORIGIN_ID.getAttr());
        }
        if(Objects.equals(originId,0L)){
            return null;
        }
        Map<Long,Double> contractMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,Double> paymentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,Double> paymentSheetMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("invoiceId",originId);
        map.put("corpid",corpid);
        map.put("del",BasicConstant.ZERO);
        List<InvoiceRelationshipEntity> invoiceRelationshipList = invoiceRelationshipModel.findEntitys(map);
        if(Objects.equals(refTypeEnum,RefTypeEnum.CONTRACT)){
            invoiceRelationshipList.forEach(invoiceRelationshipEntity -> {
                contractMap.put(invoiceRelationshipEntity.getContractId(),invoiceRelationshipEntity.getMoney());
            });
            return contractMap;
        }else if(Objects.equals(refTypeEnum,RefTypeEnum.PAYMENT)){
            invoiceRelationshipList.forEach(invoiceRelationshipEntity -> {
                paymentMap.put(invoiceRelationshipEntity.getPaymentId(),invoiceRelationshipEntity.getMoney());
            });
            return paymentMap;
        }else if(Objects.equals(refTypeEnum,RefTypeEnum.PAYMENTSHEET)){
            invoiceRelationshipList.forEach(invoiceRelationshipEntity -> {
                paymentSheetMap.put(invoiceRelationshipEntity.getPaymentSheetId(),invoiceRelationshipEntity.getMoney());
            });
            return paymentSheetMap;
        }
        return null;
    }

    public void getRelationEntityToDisplay(JSONObject result, RefTypeEnum refTypeEnum,Map<Long,Object> refEntityMap,Map<Long,Double> invoiceMap,boolean isPrePaymentSheet){
        String attr = null;
        Double lastInoivceAmount = 0D;
        if(Objects.equals(refTypeEnum,RefTypeEnum.CONTRACT)){
            attr = InvoiceEnum.CONTRACT_ID.getAttr();

        }else if(Objects.equals(refTypeEnum,RefTypeEnum.PAYMENT)){
            attr = InvoiceEnum.PAYMENT_ID.getAttr();

        }else if(Objects.equals(refTypeEnum,RefTypeEnum.PAYMENTSHEET)){
            attr = InvoiceEnum.PAYMENT_SHEET_ID.getAttr();

        }
        JSONArray subJsonArray = result.getJSONArray(attr);
        JSONArray subArray = new JSONArray();
        if(CollectionsUtil.isNotEmpty(subJsonArray)) {
            for (int i = 0; i < subJsonArray.size(); i++) {
                Object object = null;
                JSONObject subJsonObject = null;
                subJsonObject = subJsonArray.getJSONObject(i);
                Long id = subJsonObject.getLong(BasicConstant.ID);
                object = refEntityMap.get(id);
                if (object instanceof ContractEntityExt) {
                    ContractEntityExt contractEntityExt = (ContractEntityExt) object;
                    JSONObject contractData = contractEntityExt.getData();
                    subJsonObject.put(ContractEnum.AMOUNT.getAttr(), contractData.getDouble(ContractEnum.AMOUNT.getAttr()));
                    lastInoivceAmount = invoiceMap.getOrDefault(contractEntityExt.getId(), 0D);
                    subJsonObject.put(ContractEnum.INVOICE_AMOUNT.getAttr(), lastInoivceAmount);
                } else if (object instanceof PaymentEntityExt) {
                    PaymentEntityExt paymentEntityExt = (PaymentEntityExt) object;
                    JSONObject paymentData = paymentEntityExt.getData();
                    subJsonObject.put(PaymentEnum.AMOUNT.getAttr(), paymentData.getDouble(PaymentEnum.AMOUNT.getAttr()));
                    lastInoivceAmount = invoiceMap.getOrDefault(paymentEntityExt.getId(), 0D);
                    subJsonObject.put(PaymentEnum.INVOICE_AMOUNT.getAttr(), lastInoivceAmount);
                    subJsonObject.put(InvoiceEnum.CONTRACT_ID.getSaasAttr(), paymentData.getDouble(PaymentEnum.CONTRACT.getAttr()));
                } else if (object instanceof PaymentSheetEntityExt) {
                    PaymentSheetEntityExt paymentSheetEntityExt = (PaymentSheetEntityExt) object;
                    JSONObject paymentSheetData = paymentSheetEntityExt.getData();
                    subJsonObject.put(PaymentSheetEnum.AMOUNT.getAttr(), paymentSheetData.getDouble(PaymentSheetEnum.AMOUNT.getAttr()));
                    lastInoivceAmount = invoiceMap.getOrDefault(paymentSheetEntityExt.getId(), 0D);
                    subJsonObject.put(PaymentSheetEnum.INVOICE_AMOUNT.getAttr(), lastInoivceAmount);
                    if (!isPrePaymentSheet) {
                        subJsonObject.put(InvoiceEnum.CONTRACT_ID.getSaasAttr(), paymentSheetData.getJSONArray(PaymentSheetEnum.CONTRACT.getAttr()).getLong(BasicConstant.ZERO));
                    } else {
                        subJsonObject.put(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), PaymentSheetTypeEnum.PREPAYMENT.getCode());
                    }
                    subArray.add(subJsonObject);
                }
            }
        }
        if(CollectionsUtil.isNotEmpty(subArray)){
            subJsonArray.clear();
            subJsonArray.addAll(subArray);
        }
    }

    /**
     * 获取编辑时的开票金额 (第一次红冲)
     * @param relationshipGetPojo
     * @param fromRed
     */
    private void getEditInvoiceAmount(RefTypeEnum refTypeEnum,RelationshipGetPojo relationshipGetPojo,Double invoiceAmount,Integer fromRed){
        if(Objects.nonNull(relationshipGetPojo)){
            if(Objects.equals(refTypeEnum,RefTypeEnum.CONTRACT)){
                //若只有合同关联就直接放入合同的开票金额
                relationshipGetPojo.setContractInvoiceAmount(invoiceAmount);
                if(Objects.equals(fromRed,BasicConstant.ONE)){
                    //如果是红冲就给负值
                    relationshipGetPojo.setContractInvoiceAmount(-invoiceAmount);
                }
            }else if(Objects.equals(refTypeEnum,RefTypeEnum.PAYMENT)){
                relationshipGetPojo.setPaymentInvoiceAmount(invoiceAmount);
                if(Objects.equals(fromRed,BasicConstant.ONE)){
                    //如果是红冲就给负值
                    relationshipGetPojo.setPaymentInvoiceAmount(-invoiceAmount);
                }
            }else if(Objects.equals(refTypeEnum,RefTypeEnum.PAYMENTSHEET)){
                relationshipGetPojo.setPaymentSheetInvoiceAmount(invoiceAmount);
                if(Objects.equals(fromRed,BasicConstant.ONE)){
                    //如果是红冲就给负值
                    relationshipGetPojo.setPaymentSheetInvoiceAmount(-invoiceAmount);
                }
            }
        }

    }

    private Double historyInvoiceAmount(InvoiceRelationshipEntity invoiceRelationship,RefTypeEnum refTypeEnum,Long invoiceId,String corpid,List<Long> idList,Integer isEdit,boolean moreRed) throws XbbException{
        List<InvoiceRelationshipEntity> invoiceRelationshipEntityList = null;
        Double historyInvoiceAmount = 0D;
        Map<Long,Double> historyMap = null;
        if(Objects.equals(refTypeEnum,RefTypeEnum.CONTRACT)){
            if(Objects.equals(isEdit,BasicConstant.ONE) && !moreRed) {
                invoiceRelationshipEntityList = getRelationShipInvoice(invoiceId, corpid, idList, InvoiceEnum.CONTRACT_ID);
            }else if(moreRed){
                historyMap = invoiceService.getRedTotalMoneyByRef(invoiceId,corpid,invoiceRelationship.getContractId(),XbbRefTypeEnum.CONTRACT);
                historyInvoiceAmount = historyMap.getOrDefault(invoiceRelationship.getContractId(),0D);
                //invoiceRelationshipEntityList = getRedRelationShipInvoice(invoiceId,corpid,idList,InvoiceEnum.CONTRACT_ID);
            }
        }else if(Objects.equals(refTypeEnum,RefTypeEnum.PAYMENT)){
            if(Objects.equals(isEdit,BasicConstant.ONE) && !moreRed) {
                invoiceRelationshipEntityList = getRelationShipInvoice(invoiceId, corpid, idList, InvoiceEnum.PAYMENT_ID);
            }else if(moreRed){
                historyMap = invoiceService.getRedTotalMoneyByRef(invoiceId,corpid,invoiceRelationship.getPaymentId(),XbbRefTypeEnum.PAYMENT);
                historyInvoiceAmount = historyMap.getOrDefault(invoiceRelationship.getPaymentId(),0D);
                //invoiceRelationshipEntityList = getRedRelationShipInvoice(invoiceId,corpid, idList, InvoiceEnum.PAYMENT_ID);
            }
        }else if(Objects.equals(refTypeEnum,RefTypeEnum.PAYMENTSHEET)){
            if(Objects.equals(isEdit,BasicConstant.ONE) && !moreRed) {
                invoiceRelationshipEntityList = getRelationShipInvoice(invoiceId, corpid, idList, InvoiceEnum.PAYMENT_SHEET_ID);
            }else if(moreRed){
                historyMap = invoiceService.getRedTotalMoneyByRef(invoiceId,corpid,invoiceRelationship.getPaymentSheetId(),XbbRefTypeEnum.PAYMENT_SHEET);
                historyInvoiceAmount = historyMap.getOrDefault(invoiceRelationship.getPaymentSheetId(),0D);
                //invoiceRelationshipEntityList =  getRedRelationShipInvoice(invoiceId,corpid, idList, InvoiceEnum.PAYMENT_SHEET_ID);
            }
        }
        if(CollectionsUtil.isNotEmpty(invoiceRelationshipEntityList)) {
            for (InvoiceRelationshipEntity invoiceRelationshipEntity : invoiceRelationshipEntityList) {
                if(Objects.nonNull(invoiceRelationshipEntity.getMoney())){
                    historyInvoiceAmount += invoiceRelationshipEntity.getMoney();
                }
            }
        }
        Double invoiceAmount = 0D;
        if(Objects.nonNull(invoiceRelationship)){
            if(Objects.nonNull(invoiceRelationship.getMoney())){
                invoiceAmount = invoiceRelationship.getMoney();
            }
        }
        if(moreRed){
            historyInvoiceAmount = invoiceAmount + historyInvoiceAmount;
        }
        return historyInvoiceAmount;
    }

    public List<InvoiceRelationshipEntity> getRelationShipInvoice(Long invoiceId, String corpid, List<Long> relationIdList, InvoiceEnum invoiceEnum) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(ParameterConstant.IS_CANCEL, 0);
        param.put("invoiceIdNot", invoiceId);
        if (Objects.equals(invoiceEnum, InvoiceEnum.CONTRACT_ID)) {
            param.put("contractIdIn", relationIdList);
        } else if (Objects.equals(invoiceEnum, InvoiceEnum.PAYMENT_ID)) {
            param.put("paymentIdIn", relationIdList);
        } else if(Objects.equals(invoiceEnum, InvoiceEnum.PAYMENT_SHEET_ID)){
            param.put("paymentSheetIdIn",relationIdList);
        }
        return invoiceRelationshipModel.findEntitys(param);
    }

    public Integer invoiceSetStatusFilterHandle(Long listGroupId){
        try {
            ListGroupEnum listGroupEnum = ListGroupEnum.getByCode(listGroupId.intValue());
            switch (listGroupEnum){
                case ALL:
                    return BasicConstant.ZERO;
                case INVOICE_NORMAL:
                    return BasicConstant.THREE;
                case INVOICE_RED:
                    return BasicConstant.ONE;
                case INVOICE_CANCEL:
                    return BasicConstant.TWO;
                case PURCHASE_INVOICE_NORMAL:
                    return BasicConstant.THREE;
                case PURCHASE_INVOICE_RED:
                    return BasicConstant.ONE;
                case PURCHASE_INVOICE_CANCEL:
                    return BasicConstant.TWO;
                default:
                    return BasicConstant.ZERO;
            }
        } catch (Exception e) {
            return BasicConstant.ZERO;
        }
    }

    public void setInvoiceAmountToDataList(JSONObject dataList,JSONArray amountDetail){
        Map<Long,JSONObject> contractMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,JSONObject> paymentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,JSONObject> paymentSheetMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if(CollectionsUtil.isNotEmpty(amountDetail)) {
            for (int i = 0; i < amountDetail.size(); i++) {
                JSONObject amountObject = amountDetail.getJSONObject(i);
                if (CollectionsUtil.isNotEmpty(amountObject.getJSONArray(InvoiceEnum.CONTRACT_ID.getAttr()))
                        && amountObject.getJSONArray(InvoiceEnum.CONTRACT_ID.getAttr()).size() > 0) {
                    JSONObject contractAttr = amountObject.getJSONArray(InvoiceEnum.CONTRACT_ID.getAttr()).getJSONObject(0);
                    JSONObject contractInvoice = new JSONObject();
                    Long contractId = contractAttr.getLong(BasicConstant.ID);
                    contractInvoice.put(ContractEnum.AMOUNT.getAttr(), contractAttr.getDouble(ContractEnum.AMOUNT.getAttr()));
                    contractInvoice.put(ContractEnum.INVOICE_AMOUNT.getAttr(), contractAttr.getDouble(ContractEnum.INVOICE_AMOUNT.getAttr()));
                    if (Objects.nonNull(contractId)) {
                        contractMap.put(contractAttr.getLong(BasicConstant.ID), contractInvoice);
                    }
                }
                if (CollectionsUtil.isNotEmpty(amountObject.getJSONArray(InvoiceEnum.PAYMENT_ID.getAttr()))
                        && amountObject.getJSONArray(InvoiceEnum.PAYMENT_ID.getAttr()).size() > 0) {
                    JSONObject paymentAttr = amountObject.getJSONArray(InvoiceEnum.PAYMENT_ID.getAttr()).getJSONObject(0);
                    JSONObject paymentInvoice = new JSONObject();
                    Long paymentId = paymentAttr.getLong(BasicConstant.ID);
                    paymentInvoice.put(PaymentEnum.AMOUNT.getAttr(), paymentAttr.getDouble(PaymentEnum.AMOUNT.getAttr()));
                    paymentInvoice.put(PaymentEnum.INVOICE_AMOUNT.getAttr(), paymentAttr.getDouble(PaymentEnum.INVOICE_AMOUNT.getAttr()));
                    paymentInvoice.put(InvoiceEnum.CONTRACT_ID.getSaasAttr(), paymentAttr.getLong(InvoiceEnum.CONTRACT_ID.getSaasAttr()));
                    if (Objects.nonNull(paymentId)) {
                        paymentMap.put(paymentAttr.getLong(BasicConstant.ID), paymentInvoice);
                    }
                }
                if (CollectionsUtil.isNotEmpty(amountObject.getJSONArray(InvoiceEnum.PAYMENT_SHEET_ID.getAttr()))
                        && amountObject.getJSONArray(InvoiceEnum.PAYMENT_SHEET_ID.getAttr()).size() > 0) {
                    JSONObject paymentSheetAttr = amountObject.getJSONArray(InvoiceEnum.PAYMENT_SHEET_ID.getAttr()).getJSONObject(0);
                    JSONObject paymentSheetInvoice = new JSONObject();
                    Long paymentSheetId = paymentSheetAttr.getLong(BasicConstant.ID);
                    String paymentSheetSerialNo = paymentSheetAttr.getString(BasicConstant.NAME);
                    paymentSheetInvoice.put(BasicConstant.ID,paymentSheetId);
                    paymentSheetInvoice.put(BasicConstant.NAME,paymentSheetSerialNo);
                    paymentSheetInvoice.put(PaymentSheetEnum.AMOUNT.getAttr(), paymentSheetAttr.getDouble(PaymentSheetEnum.AMOUNT.getAttr()));
                    paymentSheetInvoice.put(PaymentSheetEnum.INVOICE_AMOUNT.getAttr(), paymentSheetAttr.getDouble(PaymentSheetEnum.INVOICE_AMOUNT.getAttr()));
                    paymentSheetInvoice.put(InvoiceEnum.CONTRACT_ID.getSaasAttr(), paymentSheetAttr.getLong(InvoiceEnum.CONTRACT_ID.getSaasAttr()));
                    paymentSheetInvoice.put(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(),paymentSheetAttr.getString(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr()));
                    if (Objects.nonNull(paymentSheetId)) {
                        paymentSheetMap.put(paymentSheetAttr.getLong(BasicConstant.ID), paymentSheetInvoice);
                    }
                }
            }
        }
        if(Objects.nonNull(dataList)){
            if(CollectionsUtil.isNotEmpty(dataList.getJSONArray(InvoiceEnum.CONTRACT_ID.getAttr()))){
                for(int i=0;i<dataList.getJSONArray(InvoiceEnum.CONTRACT_ID.getAttr()).size();i++){
                    JSONObject contractObject = dataList.getJSONArray(InvoiceEnum.CONTRACT_ID.getAttr()).getJSONObject(i);
                    Long contractId = contractObject.getLong(BasicConstant.ID);
                    if(Objects.nonNull(contractMap.get(contractId))) {
                        contractObject.putAll(contractMap.get(contractId));
                    }
                }
            }
            if(CollectionsUtil.isNotEmpty(dataList.getJSONArray(InvoiceEnum.PAYMENT_ID.getAttr()))) {
                for (int i = 0; i < dataList.getJSONArray(InvoiceEnum.PAYMENT_ID.getAttr()).size(); i++) {
                    JSONObject paymentJson = dataList.getJSONArray(InvoiceEnum.PAYMENT_ID.getAttr()).getJSONObject(i);
                    Long paymentId = paymentJson.getLong(BasicConstant.ID);
                    if(Objects.nonNull(paymentMap.get(paymentId))) {
                        paymentJson.putAll(paymentMap.get(paymentId));
                    }
                }
            }
            if(CollectionsUtil.isNotEmpty(dataList.getJSONArray(InvoiceEnum.PAYMENT_SHEET_ID.getAttr()))) {
                JSONArray paymentSheetArray = new JSONArray();
                for (int i = 0; i < dataList.getJSONArray(InvoiceEnum.PAYMENT_SHEET_ID.getAttr()).size(); i++) {
                    JSONObject paymentSheetJson = dataList.getJSONArray(InvoiceEnum.PAYMENT_SHEET_ID.getAttr()).getJSONObject(i);
                    Long paymentSheetId = paymentSheetJson.getLong(BasicConstant.ID);
                    if(Objects.nonNull(paymentSheetMap.get(paymentSheetId))) {
                        paymentSheetArray.add(paymentSheetMap.get(paymentSheetId));
                    }
                }
                JSONArray paymentSheetOldArray = dataList.getJSONArray(InvoiceEnum.PAYMENT_SHEET_ID.getAttr());
                paymentSheetOldArray.clear();
                paymentSheetOldArray.addAll(paymentSheetArray);
            }
        }
    }

    /**
     * 查询回/付款单list
     * @param dataIdList 回/付款单id集合
     * @param corpid 公司id
     * @param xbbRefTypeEnum 回/付款单业务类型枚举
     * @param indexTypeEnum 回/付款单es索引
     * @return java.util.List<com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt>
     * @throws XbbException
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    public List<PaasFormDataEntityExt> getPaasFormDataList4Sheet(List<Long> dataIdList, String corpid, XbbRefTypeEnum xbbRefTypeEnum, IndexTypeEnum indexTypeEnum) throws XbbException {
        List<PaasFormDataEntityExt> sheetList = paasEsModel.getByIdList(dataIdList,corpid, SaasMarkEnum.SAAS.getCode(), xbbRefTypeEnum.getCode(), new ArrayList<>(), indexTypeEnum);
        if (Objects.isNull(sheetList)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);
        }
        // 兼容es有，数据库没有的情况-原处理人：饶龙。从PaymentSheetServiceImpl移入，并兼容付款单
        List<Long> esIds = new ArrayList<>();
        if (!sheetList.isEmpty()) {
            List<Long> dbId = new ArrayList<>();
            for (PaasFormDataEntityExt entityExt : sheetList) {
                dbId.add(entityExt.getId());
            }
            for (Long id : dataIdList) {
                if (!dbId.contains(id)) {
                    esIds.add(id);
                }
            }
        } else {
            esIds = dataIdList;
        }
        if (!esIds.isEmpty()) {
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termsQuery("dataId", esIds));
            List<PaasFormDataEntityExt> esPayments = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaasFormDataEntityExt.class, null);
            if (CollectionsUtil.isNotEmpty(esPayments)) {
                sheetList.addAll(esPayments);
            }
        }
        return sheetList;
    }

    public String strRemoveCommas(String str) {
        if (str.contains(PaasConstant.COMMAS)) {
            return str.replace(",", "");
        }
        return str;
    }
    /*
     * 产品查询，sku查询带上spuId,兼容老数据
     * @param conditions
     * @param corpid
     */
    public void selectProductCondition(List<ConditionsEntityExt> conditions,String corpid) throws XbbException {
        saasLinkProductHelp.selectProductCondition(conditions, corpid);
    }

    /**
     * 组装回款单父子关系
     * @param formDataListDTO 入参
     * @param uuids uuid集合
     * @param list 回款单集合
     * @param parentIdToChildPaymentSheetIds 父子关系map
     * @param refObjectIdList 回款单ID集合
     * @throws XbbException error
     * @author zhouwq
     * @date 2020/1/10 15:12
     */
    private void assemblePaymentSheetRelation(FormDataListDTO formDataListDTO, Set<String> uuids, List<PaasFormDataEntityExt> list, Map<Long, Set<Long>> parentIdToChildPaymentSheetIds, List<Long> refObjectIdList, XbbRefTypeEnum businessType) throws XbbException {
        switch (businessType) {
            case PAYMENT_SHEET:
                List<PaasFormDataEntityExt> childPaymentSheets = fundHelp.getParentAndChildEsDataListByUuids(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET, formDataListDTO.getCorpid(), uuids);
                list.forEach(parentPaymentSheet -> childPaymentSheets.forEach(childPaymentSheet -> {
                    if (Objects.equals(childPaymentSheet.getUuid(), parentPaymentSheet.getUuid())) {
                        if (parentIdToChildPaymentSheetIds.get(parentPaymentSheet.getId()) == null) {
                            Set<Long> singleChildId = new HashSet<>();
                            singleChildId.add(childPaymentSheet.getId());
                            parentIdToChildPaymentSheetIds.put(parentPaymentSheet.getId(), singleChildId);
                        } else {
                            Set<Long> childPaymentSheetIds = parentIdToChildPaymentSheetIds.get(parentPaymentSheet.getId());
                            childPaymentSheetIds.add(childPaymentSheet.getId());
                        }
                    }
                }));
                childPaymentSheets.forEach(e -> refObjectIdList.add(e.getId()));
                break;
            case PAY_SHEET:
                childPaymentSheets = fundHelp.getParentAndChildEsDataListByUuids(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET, formDataListDTO.getCorpid(), uuids);
                list.forEach(parentPaymentSheet -> childPaymentSheets.forEach(childPaymentSheet -> {
                    if (Objects.equals(childPaymentSheet.getUuid(), parentPaymentSheet.getUuid())) {
                        if (parentIdToChildPaymentSheetIds.get(parentPaymentSheet.getId()) == null) {
                            Set<Long> singleChildId = new HashSet<>();
                            singleChildId.add(childPaymentSheet.getId());
                            parentIdToChildPaymentSheetIds.put(parentPaymentSheet.getId(), singleChildId);
                        } else {
                            Set<Long> childPaymentSheetIds = parentIdToChildPaymentSheetIds.get(parentPaymentSheet.getId());
                            childPaymentSheetIds.add(childPaymentSheet.getId());
                        }
                    }
                }));
                childPaymentSheets.forEach(e -> refObjectIdList.add(e.getId()));
                break;
            default:
                break;
        }

    }

    /**
     * 处理列表页特殊筛选
     *
     * @param formDataListDTO 入参
     * @throws XbbException error
     * @author long.rao
     * @date 2020/2/26 15:12
     */
    public void commonFilter(FormDataListDTO formDataListDTO) throws XbbException {
        if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
            // 范围筛选仅支持web端
            return;
        }
        JSONObject commonFilter = formDataListDTO.getCommonFilter();
        if (Objects.isNull(commonFilter)) {
            return;
        }
        JSONObject rangeScreen = commonFilter.getJSONObject(RangeScreenConstant.RANGE_SCREEN);
        if (Objects.isNull(rangeScreen) || Objects.isNull(rangeScreen.get(RangeScreenConstant.TYPE)) || StringUtil.isEmpty(rangeScreen.getString(RangeScreenConstant.TYPE)) || Objects.isNull(rangeScreen.get(RangeScreenConstant.VALUE))) {
            return;
        }

        String type;
        List<String> values;
        String attr;
        try {
            type = rangeScreen.getString(RangeScreenConstant.TYPE);
            values = rangeScreen.getJSONArray(RangeScreenConstant.VALUE).toJavaList(String.class);
            attr = rangeScreen.getString(RangeScreenConstant.ATTR);
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), "saasListHelp.commonFilter中的commonFilter参数错误");
        }

        if (CollectionsUtil.isEmpty(values)) {
            return;
        }
        Integer businessType = formDataListDTO.getBusinessType();
        // 竞争对手不需要再去获取该部门下的员工id，有专门存储可见部门的字段，产品也是一样
        if (Objects.equals(type, RangeScreenConstant.DEPARTMENT) && !XbbRefTypeEnum.hasVisibleRangeBusiness().contains(businessType) && !Objects.equals(businessType, XbbRefTypeEnum.COMPETITOR.getCode())) {
            List<Long> deptIds = new ArrayList<>(values.size());
            values.forEach(item -> deptIds.add(Long.valueOf(item)));
            values = userModel.getUserIdsRecursionDep(deptIds, formDataListDTO.getCorpid(), 1, true);
        }
        if (CollectionsUtil.isEmpty(values)) {
            // 预防部门下没有员工，给个userId为"0"的，防止条件失效
            values = Arrays.asList("0");
        }
        List<ConditionsEntityExt> conditionsEntityExtList = formDataListDTO.getConditions();
        conditionsEntityExtList = conditionsEntityExtList == null ? new ArrayList<>() : conditionsEntityExtList;
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
        Integer fieldType = 0;
        XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        switch (refTypeEnum) {
            case CUSTOMER_MANAGEMENT:
            case CONTACT:
            case SALES_OPPORTUNITY:
            case REFUND:
            case PAYMENT:
            case PAY_PLAN:
            case INVOICE:
            case PURCHASE_INVOICE:
            case SUPPLIER_CONTACT:
            case RETURNED_PURCHASE:
            case ASSEMBLE:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
            case CONTRACT_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case INVENTORY:
            case TRANSFER:
            case SUPPLIER:
            case BOM_BILL:
            case PRODUCTION_ORDER:
            case PAYMENT_SHEET:
            case PAY_SHEET:
            case DISTRIBUTOR_CONTACT:
            case DISTRIBUTOR_MANAGEMENT:
            case RETURN:
            case CLUE:
            case MARKET_ACTIVITY:
                if (Objects.equals(attr, FieldTypeEnum.OWNERID.getAlias())) {
                    fieldType = FieldTypeEnum.OWNERID.getType();
                } else if (Objects.equals(attr, PaymentSheetEnum.BELONG_ID.getAttr()) || Objects.equals(attr, PaySheetEnum.BELONG_ID.getAttr())) {
                    fieldType = FieldTypeEnum.USER_GROUP.getType();
                } else {
                    fieldType = FieldTypeEnum.COUSERID.getType();
                }
                conditionsEntityExt = new ConditionsEntityExt(attr, "", fieldType, ConditionEnum.IN.getSymbol(), new ArrayList<>(values));
                break;
            case WORK_ORDER:
            case RECEIPT_ORDER:
                if (Objects.equals(attr, FieldTypeEnum.OWNERID.getAlias())) {
                    fieldType = FieldTypeEnum.OWNERID.getType();
                } else if (Objects.equals(attr, FieldTypeEnum.COUSERID.getAlias())) {
                    fieldType = FieldTypeEnum.COUSERID.getType();
                } else if (Objects.equals(attr, FieldTypeEnum.CREATORID.getAlias())){
                    fieldType = FieldTypeEnum.CREATORID.getType();
                } else {
                    break;
                }
                conditionsEntityExt = new ConditionsEntityExt(attr, "", fieldType, ConditionEnum.IN.getSymbol(), new ArrayList<>(values));
                break;
            case QUOTATION:
                if (Objects.equals(attr, QuotationEnum.OWNER_ID.getAttr())) {
                    fieldType = QuotationEnum.OWNER_ID.getFieldType();
                } else if (Objects.equals(attr, QuotationEnum.MINOR_USER.getAttr())) {
                    fieldType = QuotationEnum.MINOR_USER.getFieldType();
                } else if (Objects.equals(attr, QuotationEnum.QUOTATION_PERSON.getAttr())) {
                    fieldType = QuotationEnum.QUOTATION_PERSON.getFieldType();
                }
                conditionsEntityExt = new ConditionsEntityExt(attr, "", fieldType, ConditionEnum.IN.getSymbol(), new ArrayList<>(values));
                break;
            case CONTRACT:
            case ORDER:
                if (Objects.equals(attr, ContractEnum.OWNER_ID.getAttr())) {
                    fieldType = ContractEnum.OWNER_ID.getFieldType();
                } else if (Objects.equals(attr, ContractEnum.MINOR_USER.getAttr())) {
                    fieldType = ContractEnum.MINOR_USER.getFieldType();
                } else if (Objects.equals(attr, ContractEnum.SIGN_PERSON.getAttr())) {
                    fieldType = ContractEnum.SIGN_PERSON.getFieldType();
                }
                conditionsEntityExt = new ConditionsEntityExt(attr, "", fieldType, ConditionEnum.IN.getSymbol(), new ArrayList<>(values));
                break;
            case PURCHASE:
                if (Objects.equals(attr, PurchaseEnum.OWNER_ID.getAttr())) {
                    fieldType = PurchaseEnum.OWNER_ID.getFieldType();
                } else if (Objects.equals(attr, PurchaseEnum.COUSERID.getAttr())) {
                    fieldType = PurchaseEnum.COUSERID.getFieldType();
                } else if (Objects.equals(attr, PurchaseEnum.SIGNER_ID.getAttr())) {
                    fieldType = PurchaseEnum.SIGNER_ID.getFieldType();
                }
                conditionsEntityExt = new ConditionsEntityExt(attr, "", fieldType, ConditionEnum.IN.getSymbol(), new ArrayList<>(values));
                break;
            case PRODUCT:
            case SERVICE_PROJECT:
                if (Objects.equals(type, RangeScreenConstant.USER)) {
                    conditionsEntityExt = new ConditionsEntityExt(VisibleRangeEnum.VISIBLE_USER.getAttr(), "", VisibleRangeEnum.VISIBLE_USER.getFieldType(), ConditionEnum.IN.getSymbol(), new ArrayList<>(values));
                } else if (Objects.equals(type, RangeScreenConstant.DEPARTMENT)) {
                    conditionsEntityExt = new ConditionsEntityExt(VisibleRangeEnum.VISIBLE_DEPT.getAttr(), "", VisibleRangeEnum.VISIBLE_DEPT.getFieldType(), ConditionEnum.IN.getSymbol(), new ArrayList<>(values));
                }
                break;
            case COMPETITOR:
                if (Objects.equals(type, RangeScreenConstant.USER)) {
                    conditionsEntityExt = new ConditionsEntityExt(CompetitorEnum.VISBLE_USER.getAttr(), "", CompetitorEnum.VISBLE_USER.getFieldType(), ConditionEnum.IN.getSymbol(), new ArrayList<>(values));
                } else if (Objects.equals(type, RangeScreenConstant.DEPARTMENT)) {
                    conditionsEntityExt = new ConditionsEntityExt(CompetitorEnum.VISBLE_DEPT.getAttr(), "", CompetitorEnum.VISBLE_DEPT.getFieldType(), ConditionEnum.IN.getSymbol(), new ArrayList<>(values));
                }
                break;
            case CUSTOMER_COMMUNICATE:
            case SUPPLIER_COMMUNICATE:
            case DISTRIBUTOR_COMMUNICATE:
                conditionsEntityExt = new ConditionsEntityExt(FieldTypeEnum.CREATORID.getAlias(), "",
                        FieldTypeEnum.CREATORID.getType(), ConditionEnum.IN.getSymbol(), new ArrayList<>(values));
                break;
            case SYSTEM:
                conditionsEntityExt = new ConditionsEntityExt(FieldTypeEnum.OWNERID.getAlias(), "",
                        FieldTypeEnum.OWNERID.getType(), ConditionEnum.IN.getSymbol(), new ArrayList<>(values));
                break;
            default:
                // 没列出来的，要不就是在别的地方单独处理，要不就是不支持
                break;
        }
        conditionsEntityExtList.add(conditionsEntityExt);
        formDataListDTO.setConditions(conditionsEntityExtList);
    }



    /**
     * 按照评分区间筛选时，把value转为条件
     *
     * @param
     * @return
     */
    public void handleScoreRangeCondition(String corpid ,Long formId , Integer businessType,List<ConditionsEntityExt> conditions) throws XbbException {

        if (!marketManagementBusinessHelp.feeTypeIsStandardOrAppIsClosed(corpid) && CollectionsUtil.isNotEmpty(conditions)) {
            for (int i = conditions.size() - 1; i >= 0; i--) {
                ConditionsEntityExt screenCondition = conditions.get(i);
                String attr = screenCondition.getAttr();
                List<Object> values = screenCondition.getValue();
                ConditionEnum conditionEnum = ConditionEnum.getConditionEnum(screenCondition.getSymbol());
                //展示方式是按照区间展示时
                if(scoreRangeModel.isRangWithScoreShowType(corpid,formId) && CollectionsUtil.isNotEmpty(values)){
                    //筛选的字段是评分业务的字段
                    if(((Objects.equals(attr,CustomerManagementEnum.SCORE.getAttr()) &&  Objects.equals(businessType,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) ||
                            (Objects.equals(attr,ClueEnum.SCORE.getAttr()) &&  Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())))){
                        try {
                            //查询评分展示区间。
                            ScoreRangeDetailVO scoreRange = scoreRangeService.getScoreRange(new ScoreRangeDetailDTO(corpid, formId));
                            List<ScoreRangeConditionEntity> scoreRangeList = scoreRange.getScoreRangeList();
                            //评分区间的value  就是 scoreRangeList 的index
                            if(CollectionsUtil.isNotEmpty(scoreRangeList)){
                                ScoreRangeConditionEntity scoreRangeCondition = scoreRangeList.get((Integer)(values.get(0)));
                                screenCondition.setSymbol(scoreRangeCondition.getSymbol());
                                screenCondition.setValue(scoreRangeCondition.getValue());
                            }
                        } catch (XbbException e) {
                            Log.error("handleScoreRangeCondition 异常e-{}-",e.getMessage());
                            return;
                        }
                    }
                }

            }
        }
    }


   public List<ConditionsEntityExt> parseCommonFilter(FormDataListDTO formDataListDTO,List<ConditionsEntityExt> conditionList){
        //pc端传的source参数是放commonFilter里，但是dingtalk端传的source参数是放在conditions里面的
        String platform = formDataListDTO.getPlatform();
        if (Objects.equals(platform, PlatFormEnum.WEB.getValue())) {
            JSONObject commonFilter = formDataListDTO.getCommonFilter();
            if(Objects.nonNull(commonFilter)){
                JSONObject sourceObject = commonFilter.getJSONObject(FieldTypeEnum.SOURCE.getAlias());
                if(Objects.nonNull(sourceObject)){
                    Integer value = sourceObject.getInteger("value");
                    if(Objects.nonNull(value)) {
                        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(PaymentEnum.SOURCE.getAttr(), "", PaymentEnum.SOURCE.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(value));
                        conditionList.add(conditionsEntityExt);
                        if (Objects.equals(sourceObject.getString("attr"), PaymentSourceTypeEnum.INVOICE.getAttr())) {
                            ConditionsEntityExt conditions = new ConditionsEntityExt(PaymentEnum.SOURCE_REF_TYPE.getAttr(), "", PaymentEnum.SOURCE_REF_TYPE.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(XbbRefTypeEnum.INVOICE.getCode()));
                            conditionList.add(conditions);
                        } else if (Objects.equals(sourceObject.getString("attr"), PaymentSourceTypeEnum.OUTSTOCK.getAttr())) {
                            ConditionsEntityExt conditions = new ConditionsEntityExt(PaymentEnum.SOURCE_REF_TYPE.getAttr(), "", PaymentEnum.SOURCE_REF_TYPE.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode()));
                            conditionList.add(conditions);
                        }
                    }
                }
            }
            return conditionList;
        }else if (Objects.equals(platform, PlatFormEnum.DINGTALK.getValue())) {
            List<ConditionsEntityExt> newConditionList = new ArrayList<>();
            for (ConditionsEntityExt conditionsEntityExt : conditionList) {
                if (PaymentEnum.SOURCE.getAttr().equals(conditionsEntityExt.getAttr())) {
                    ConditionsEntityExt conditionsEntityExtSen = new ConditionsEntityExt(PaymentEnum.SOURCE.getAttr(), "", PaymentEnum.SOURCE.getFieldType(), ConditionEnum.EQUAL.getSymbol(), conditionsEntityExt.getValue());
                    newConditionList.add(conditionsEntityExtSen);
                    ConditionsEntityExt conditions = new ConditionsEntityExt();
                    if (Objects.equals(conditionsEntityExt.getSubAttr(), PaymentSourceTypeEnum.INVOICE.getAttr())) {
                        conditions = new ConditionsEntityExt(PaymentEnum.SOURCE_REF_TYPE.getAttr(), "", PaymentEnum.SOURCE_REF_TYPE.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(XbbRefTypeEnum.INVOICE.getCode()));
                    } else if (Objects.equals(conditionsEntityExt.getSubAttr(), PaymentSourceTypeEnum.OUTSTOCK.getAttr())) {
                        conditions = new ConditionsEntityExt(PaymentEnum.SOURCE_REF_TYPE.getAttr(), "", PaymentEnum.SOURCE_REF_TYPE.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode()));
                    }
                    newConditionList.add(conditions);
                }else {
                    newConditionList.add(conditionsEntityExt);
                }
            }
            return newConditionList;
        }
        return conditionList;
   }

    /**
     * 把查询客户列表的相关参数、及fieldList等信息塞入
     * @param formDataListDTO 列表查询dto
     * @param customerIdIn 对账日期范围内的客户id集合
     * @param fieldList 要查询的客户字段
     * @throws XbbException
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    public void getFormDataListDTO4Statement(FormDataListDTO formDataListDTO, List<Object> customerIdIn, List<String> fieldList) throws XbbException {
        int businessType = XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode();
        int subBusinessType = XbbRefTypeEnum.CUSTOMER.getCode();
        formDataListDTO.setBusinessType(businessType);
        formDataListDTO.setSubBusinessType(subBusinessType);
        //重置conditions，因为前端传入的是对账单关联客户字段，而此处是要去查客户本身不是差对账单表
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        formDataListDTO.setConditions(conditionList);
        /*
        //需过滤客户列表数据权限
        TransmittableThreadLocalUtil.setValue(formDataListDTO.getSaasMark(), businessType, formDataListDTO.getMenuId(), formDataListDTO.getDistributorMark());
        saasListDataPermissionHelp.listDataPermission(conditionList, formDataListDTO.getLoginUser(), businessType, subBusinessType);
        */
        //处理范围筛选
        commonFilter(formDataListDTO);
        //塞入客户id集合
        conditionList.add(new ConditionsEntityExt(FieldTypeEnum.DATAID.getAlias(), "", FieldTypeEnum.DATAID.getType(), ConditionEnum.IN.getSymbol(), customerIdIn));
        formDataListDTO.setFieldList(fieldList);
    }

    /**
     * @param corpid
     * @param groupId 多单位产品组id
     * @return
     * @throws XbbException
     */
    private Map<String, String> getUnitMap4Product(String corpid, Long groupId) throws XbbException {
        Map<String, String> unitMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        ProductFieldPojo productFieldPojo = saasFormHelp.getProductFieldPojo(RedisPrefixConstant.PRODUCT_UNIT, ProductEnum.UNIT.getAttr(), corpid);
        //单单位
        if (Objects.isNull(groupId) || Objects.equals(groupId, 0L)) {
            List<ItemPoJo> singleItems = productFieldPojo.getSingleItems();
            singleItems.forEach(item -> unitMap.put(item.getValue().toString(), item.getText()));
            return unitMap;
        }
        //多单位
        List<MultiUnitItemPoJo> multiItems = productFieldPojo.getMultiItems();
        multiItems.forEach(item -> unitMap.put(item.getValue().toString(), item.getBaseName()));
        return unitMap;
    }

    /**
     * @Author: wujian
     * @Description: 待采购合同+产品视图列表数据可见处理
     * @Date: 下午2:00 2021/10/14
     * @Param: []
     * @return: void
     **/
    public void praseCanseeWaitPurchaseProductData(FormDataListDTO formDataListDTO,PaasFormDataEsListVO formDataListVO,Map<String, List<FieldAttrEntity>> needCanSeeExplainMap, List<Long> contractIdList) throws XbbException {
        UserVO loginUser = formDataListDTO.getLoginUser();
        String userId = formDataListDTO.getUserId();
        String corpid = formDataListDTO.getCorpid();
        // 封装好的数据
        List<PaasFormDataEntityExt> paasFormDataESList = formDataListVO.getPaasFormDataESList();
        // 需要处理可见的解释
        List<FieldAttrEntity> contractFieldList = needCanSeeExplainMap.get("contract");
        List<FieldAttrEntity> productFieldList = needCanSeeExplainMap.get("product");
//        contractFieldList.addAll(productFieldList);
        // 合同负责人协同人数据
        Map<String,Object> contractUserparam = new HashMap<>();
        contractUserparam.put("corpid",corpid);
        contractUserparam.put("del",0);
        contractUserparam.put("contractIdIn",contractIdList);
        List<ContractUserEntity> contractUserEntityList = contractUserModel.findEntitys(contractUserparam);
        // 负责人Map
        Map<Long,List<String>> ownerMap = new HashMap<>();
        // 协同人Map
        Map<Long,List<String>> coUserMap = new HashMap<>();
        // 封装合同数据的负责人协同人数据
        if (CollectionsUtil.isNotEmpty(contractUserEntityList)){
            for (ContractUserEntity contractUserEntity : contractUserEntityList) {
                Integer isMain = contractUserEntity.getIsMain();
                Long contractId = contractUserEntity.getDataId();
                if (Objects.equals(isMain,1)){
                    if (ownerMap.containsKey(contractId)){
                        List<String> list = ownerMap.get(contractId);
                        list.add(userId);
                        ownerMap.put(contractId,list);
                    }else{
                        List<String> owenList = new ArrayList<>();
                        owenList.add(userId);
                        ownerMap.put(contractId,owenList);
                    }

                }else {
                    if (coUserMap.containsKey(contractId)){
                        List<String> list = coUserMap.get(contractId);
                        list.add(userId);
                        coUserMap.put(contractId,list);
                    }else{
                        List<String> coList = new ArrayList<>();
                        coList.add(userId);
                        coUserMap.put(contractId,coList);
                    }
                }
            }
        }

        // 处理产品的可见
        if (CollectionUtils.isNotEmpty(productFieldList)){
            Map<String, FieldAttrEntity> expalinMap = ExplainUtil.getExplainMapByList(productFieldList);
            ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            userAndDepartmentGetDTO.setLoginUser(loginUser);
            userAndDepartmentGetDTO.setUserId(userId);
            userAndDepartmentGetDTO.setCorpid(formDataListDTO.getCorpid());
            UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
            Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
            Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
            parseSingleRowDataDTO.setExplainMap(expalinMap);
            parseSingleRowDataDTO.setUserMap(userMap);
            parseSingleRowDataDTO.setDepartmentMap(departmentMap);
            parseSingleRowDataDTO.setLoginUser(loginUser);
            parseSingleRowDataDTO.setUserId(userId);
            parseSingleRowDataDTO.setCorpid(formDataListDTO.getCorpid());
            for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
                JSONObject data = paasFormDataEntityExt.getData();
                String creatorId = data.getString("productCreatId");
                Map<String, Boolean> contractDataCanseeMap = parseCanseeParam(productFieldList, creatorId,new ArrayList<>(),new ArrayList<>(),parseSingleRowDataDTO);
                for (Map.Entry<String, Boolean> stringBooleanEntry : contractDataCanseeMap.entrySet()) {
                    String key = stringBooleanEntry.getKey();
                    Boolean value = stringBooleanEntry.getValue();
                    if (!value){
                        if (Objects.equals(ProductEnum.PRODUCT_IMGS.getAttr(),key)){
                            data.put(ProductEnum.PRODUCT_IMGS.getAttr(),null);
                        }else if ((Objects.equals("productName",key))){
                            data.put("productName",null);
                            data.put("name", null);
                        }else if ((Objects.equals("productSerialNo",key))){
                            data.put("productSerialNo",null);
                        }else if ((Objects.equals(ProductEnum.SPECIFICATION.getAttr(),key))){
                            data.put(ProductEnum.SPECIFICATION.getAttr(),null);
                        }else if ((Objects.equals(ProductEnum.SUPPLIER.getAttr(),key))){
                            data.put(ProductEnum.SUPPLIER.getAttr(),new JSONArray());
                        }
                    }
                }
            }
        }
        // 处理合同数据可见
        if (CollectionsUtil.isNotEmpty(contractFieldList)){
            Map<String, FieldAttrEntity> expalinMap = ExplainUtil.getExplainMapByList(contractFieldList);
            ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            userAndDepartmentGetDTO.setLoginUser(loginUser);
            userAndDepartmentGetDTO.setUserId(userId);
            userAndDepartmentGetDTO.setCorpid(formDataListDTO.getCorpid());
            UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
            Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
            Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
            parseSingleRowDataDTO.setExplainMap(expalinMap);
            parseSingleRowDataDTO.setUserMap(userMap);
            parseSingleRowDataDTO.setDepartmentMap(departmentMap);
            parseSingleRowDataDTO.setLoginUser(loginUser);
            parseSingleRowDataDTO.setUserId(userId);
            parseSingleRowDataDTO.setCorpid(formDataListDTO.getCorpid());
            for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
                JSONObject data = paasFormDataEntityExt.getData();
                Long contractId = data.getLong("contractId");
                String creatorId = data.getString("contractCreatId");
                // 负责人集合
                List<String> ownerIdList = ownerMap.getOrDefault(contractId,new ArrayList<>());
                // 协同人集合
                List<String> minorIdList = coUserMap.getOrDefault(contractId,new ArrayList<>());
                Map<String, Boolean> contractDataCanseeMap = parseCanseeParam(contractFieldList, creatorId,ownerIdList,minorIdList,parseSingleRowDataDTO);
                // 处理合同的数据可见
                for (Map.Entry<String, Boolean> stringBooleanEntry : contractDataCanseeMap.entrySet()) {
                    String key = stringBooleanEntry.getKey();
                    Boolean value = stringBooleanEntry.getValue();
                    if (!value){
                        if (Objects.equals(ContractEnum.CONTRACT_NO.getAttr(),key)){
                            data.put(ContractEnum.CONTRACT_NO.getAttr(),null);
                        }else if (Objects.equals(ContractEnum.NAME.getAttr(),key)){
                            data.put(ContractEnum.NAME.getAttr(),null);
                        }else if (Objects.equals(ContractEnum.LINK_CUSTOMER.getAttr(),key)){
                            data.put(ContractEnum.LINK_CUSTOMER.getAttr(),new JSONArray());
                        }else if (Objects.equals(ContractEnum.CREATOR_ID.getAttr(),key)){
                            data.put(ContractEnum.CREATOR_ID.getAttr(),null);
                        }else if (Objects.equals(ContractEnum.ADD_TIME.getAttr(),key)){
                            data.put(ContractEnum.ADD_TIME.getAttr(),null);
                        }else if (Objects.equals(ContractEnum.UPDATE_TIME.getAttr(),key)){
                            data.put(ContractEnum.UPDATE_TIME.getAttr(),null);
                        }else if (Objects.equals(ContractProductEnum.UNIT.getAttr(),key)){
                            data.put(ContractProductEnum.UNIT.getAttr(),null);
                            data.put(ProductConstant.TRANSFORM_UNIT_RATE, null);
                        }else if (Objects.equals(ContractProductEnum.MEMO.getAttr(),key)){
                            data.put(ContractProductEnum.MEMO.getAttr(),null);
                        }else if (Objects.equals(ContractProductEnum.NUM.getAttr(),key)){
                            data.put(ContractProductEnum.NUM.getAttr(),null);
                        }else if ((Objects.equals(ContractProductEnum.OUTSTOCK_NUM.getAttr(),key))){
                            data.put("outstockNum",null);
                        }else if ((Objects.equals(ContractProductEnum.WAIT_OUTSTOCK_NUM.getAttr(),key))){
                            data.put("waitOutstockNum",null);
                        }
                    }
                }


            }
        }
    }


    /**
     * @Author: wujian
     * @Description: 处理待采购产品详情数据可见
     * @Date: 下午2:33 2021/9/18
     * @Param: [waitPurchaseProductList, headListExplain]
     * @return: java.util.List<com.xbongbong.pro.weblist.pojo.WaitPurchaseProductPojo>
     **/
    public List<WaitPurchaseProductPojo> parseCanseeData(List<WaitPurchaseProductPojo> waitPurchaseProductList, List<FieldAttrEntity> headListExplain, UserVO loginUser,Map<Long,List<String>> ownerMap,Map<Long,List<String>> coUserMap) throws XbbException {
        if (CollectionsUtil.isNotEmpty(waitPurchaseProductList)){
            Map<String, FieldAttrEntity> expalinMap = ExplainUtil.getExplainMapByList(headListExplain);
            ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            userAndDepartmentGetDTO.setLoginUser(loginUser);
            userAndDepartmentGetDTO.setUserId(loginUser.getUserId());
            userAndDepartmentGetDTO.setCorpid(loginUser.getCorpid());
            UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
            Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
            Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
            parseSingleRowDataDTO.setExplainMap(expalinMap);
            parseSingleRowDataDTO.setUserMap(userMap);
            parseSingleRowDataDTO.setDepartmentMap(departmentMap);
            parseSingleRowDataDTO.setLoginUser(loginUser);
            parseSingleRowDataDTO.setUserId(loginUser.getUserId());
            parseSingleRowDataDTO.setCorpid(loginUser.getCorpid());
            for (WaitPurchaseProductPojo waitPurchaseProductPojo : waitPurchaseProductList) {
                Long contractId = waitPurchaseProductPojo.getContractId();
                List<String> ownerList = ownerMap.getOrDefault(contractId, new ArrayList<>());
                List<String> coUserList = coUserMap.getOrDefault(contractId, new ArrayList<>());
                Map<String, Boolean> canSeeMap = parseCanseeParam(headListExplain, waitPurchaseProductPojo.getCreatorId(),ownerList,coUserList,parseSingleRowDataDTO);
                for (Map.Entry<String, Boolean> stringBooleanEntry : canSeeMap.entrySet()) {
                    String key = stringBooleanEntry.getKey();
                    Boolean value = stringBooleanEntry.getValue();
                    if (!value ){
                        if (Objects.equals(ProductEnum.SUPPLIER.getAttr(),key)){
                            waitPurchaseProductPojo.setSupplier(null);
                        }else if (Objects.equals(ContractProductEnum.UNIT.getAttr(),key)){
                            waitPurchaseProductPojo.setProductUnit(null);
                        }else if (Objects.equals(ContractProductEnum.NUM.getAttr(),key)){
                            waitPurchaseProductPojo.setMarketNum(null);
                        }else if (Objects.equals(ContractProductEnum.WAIT_OUTSTOCK_NUM.getAttr(),key)){
                            waitPurchaseProductPojo.setWaitOutstockNum(null);
                        }else if (Objects.equals(ContractProductEnum.OUTSTOCK_NUM.getAttr(),key)){
                            waitPurchaseProductPojo.setOutstockNum(null);
                        } else if (Objects.equals("productName",key)){
                            waitPurchaseProductPojo.setName(null);
                        }else if (Objects.equals("productSerialNo",key)){
                            waitPurchaseProductPojo.setSerialNo(null);
                        }else if (Objects.equals(ProductEnum.SPECIFICATION.getAttr(),key)){
                            waitPurchaseProductPojo.setSpecification(null);
                        }else if (Objects.equals(ProductEnum.PRODUCT_IMGS.getAttr(),key)){
                            waitPurchaseProductPojo.setProductImgs(new JSONArray());
                        }if (Objects.equals(ContractProductEnum.MEMO.getAttr(),key)){
                            waitPurchaseProductPojo.setMemo(null);
                        }if (Objects.equals(ContractEnum.NAME.getAttr(),key)){
                            waitPurchaseProductPojo.setContractName(null);
                        }if (Objects.equals(ContractEnum.CONTRACT_NO.getAttr(),key)){
                            waitPurchaseProductPojo.setContractNo(null);
                        }if (Objects.equals(ContractEnum.LINK_CUSTOMER.getAttr(),key)){
                            waitPurchaseProductPojo.setCustomer("");
                        }if (Objects.equals(ContractEnum.ADD_TIME.getAttr(),key)){
                            waitPurchaseProductPojo.setAddTime(null);
                        }if (Objects.equals(ContractEnum.UPDATE_TIME.getAttr(),key)){
                            waitPurchaseProductPojo.setUpdateTime(null);
                        }if (Objects.equals(ContractEnum.CREATOR_ID.getAttr(),key)){
                            waitPurchaseProductPojo.setCreatorId(null);
                        }
                    }
                }
            }
        }
        return waitPurchaseProductList;
    }


    /**
     * @Description: 处理待入库产品详情数据可见
     * @Date: 下午2:33 2021/9/18
     * @Param: [waitPurchaseProductList, headListExplain]
     * @return: java.util.List<com.xbongbong.pro.weblist.pojo.WaitPurchaseProductPojo>
     **/
    public WaitOutstockProductPojo parseWaitInstockCanseeData(WaitOutstockProductPojo waitOutstockProductPojo, List<FieldAttrEntity> headListExplain,  ParseSingleRowDataDTO parseSingleRowDataDTO, ProductEntityExt productEntity) throws XbbException {
                Map<String, Boolean> canSeeMap = parseCanseeParam(headListExplain, productEntity.getCreatorId(),Collections.singletonList(productEntity.getOwnerId()),new ArrayList<>(),parseSingleRowDataDTO);
                for (Map.Entry<String, Boolean> stringBooleanEntry : canSeeMap.entrySet()) {
                    String key = stringBooleanEntry.getKey();
                    Boolean value = stringBooleanEntry.getValue();
                    if (!value ){
                        if (Objects.equals(WaitInstockEnum.PRODUCT_IMGS.getAttr(),key)){
                            waitOutstockProductPojo.setProductThumnail(null);
                        }else if (Objects.equals(WaitInstockEnum.PRODUCT_NAME.getAttr(),key)){
                            waitOutstockProductPojo.setProductName(null);
                        }else if (Objects.equals(WaitInstockEnum.PRODUCT_NO.getAttr(),key)){
                            waitOutstockProductPojo.setProductNo(null);
                        }else if (Objects.equals(WaitInstockEnum.SPECIFICATION.getAttr(),key)){
                            waitOutstockProductPojo.setSpecification(null);
                        }else if (Objects.equals(WaitInstockEnum.UNIT.getAttr(),key)){
                            waitOutstockProductPojo.setUnit(null);
                        }else if (Objects.equals(WaitInstockEnum.MEMO.getAttr(),key)){
                            waitOutstockProductPojo.setMemo(null);
                        }
                    }
                }
        return waitOutstockProductPojo;
    }

    /**
     * @Description: 处理待入库产品详情数据可见
     * @Date: 下午2:33 2021/9/18
     * @Param: [waitPurchaseProductList, headListExplain]
     * @return: java.util.List<com.xbongbong.pro.weblist.pojo.WaitPurchaseProductPojo>
     **/
    public WaitOutstockProductPojo parseWaitOutStockCanseeData(WaitOutstockProductPojo waitOutstockProductPojo, List<FieldAttrEntity> contractExplain, ParseSingleRowDataDTO parseSingleRowDataDTO, PaasFormDataEntityExt contractEntityExt) throws XbbException {
        Map<String, Boolean> contractCanSeeMap = parseCanseeParam(contractExplain, contractEntityExt.getCreatorId(),Collections.singletonList(contractEntityExt.getOwnerId()),new ArrayList<>(),parseSingleRowDataDTO);
        for (Map.Entry<String, Boolean> stringBooleanEntry : contractCanSeeMap.entrySet()) {
            String key = stringBooleanEntry.getKey();
            Boolean value = stringBooleanEntry.getValue();
            if (!value) {
              if (Objects.equals(ContractProductEnum.UNIT.getAttr(), key)) {
                    waitOutstockProductPojo.setUnit("--");
                    waitOutstockProductPojo.setTransformUnitRate(null);
                    continue;
                }else if(Objects.equals(ContractProductEnum.STOCK.getAttr(), key)){
                  waitOutstockProductPojo.setStock("--");
                  continue;
              }else if(Objects.equals(ContractProductEnum.MEMO.getAttr(), key)){
                  waitOutstockProductPojo.setMemo("--");
                  continue;
              }
            }
        }
        return waitOutstockProductPojo;
    }

    /**
     * @Author: wujian
     * @Description:
     * @Date: 下午2:29 2021/10/14
     * @Param: [headListExplain需要处理可见的表头解释集合, loginUser, userId]
     * @return: java.util.Map<java.lang.String,java.lang.Boolean>
     **/
    public Map<String, Boolean> parseCanseeParam(List<FieldAttrEntity> headListExplain,String creatId,List<String> ownerId,List<String> coUserId,ParseSingleRowDataDTO parseSingleRowDataDTO) throws XbbException {

        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();

        // key=attr bollean 该字段是否有权限可见
        Map<String, Boolean> canSeeMap = new HashMap<>();
        if (CollectionsUtil.isNotEmpty(headListExplain)){
            parseSingleRowDataDTO.setCreatorId(creatId);
            parseSingleRowDataDTO.setOwnerId(ownerId);
            parseSingleRowDataDTO.setCoUserId(coUserId);
            BeanUtil.copyProperties(parseSingleRowDataDTO, handlerExplainDTO);

            // 处理列表可见权限
            for (FieldAttrEntity fieldAttrEntity : headListExplain) {
                // ture:隐藏；false：不隐藏
                boolean invisibleOfScope = ExplainUtil.invisibleOfScope(fieldAttrEntity, handlerExplainDTO);
                if (invisibleOfScope && (Objects.isNull(parseSingleRowDataDTO.getIsProcess()) || !parseSingleRowDataDTO.getIsProcess())) {
                    canSeeMap.put(fieldAttrEntity.getAttr(),false);
                }else {
                    canSeeMap.put(fieldAttrEntity.getAttr(),true);
                }
            }
        }

        return canSeeMap;
    }

    /**
     * 处理待入库产品维度列表页解释
     * @param formDataListDTO
     * @param formDataListVO
     * @return
     * @throws XbbException
     */
    public List<FieldAttrEntity> setProductFormExplain(FormDataListDTO formDataListDTO , PaasFormDataEsListVO formDataListVO) throws XbbException {
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PURCHASE.getCode(),formDataListDTO.getCorpid());
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        //处理采购合同关联产品解释
        List<FieldAttrEntity> explain = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        List<FieldAttrEntity> explainList = new ArrayList<>();
        List<FieldAttrEntity> explainSubList = new ArrayList<>();
        explain.forEach(fieldAttrEntity -> {
            if (Objects.equals(fieldAttrEntity.getAttr(), PurchaseEnum.PRODUCT.getAttr())){
                List<FieldAttrEntity> items = (List<FieldAttrEntity>) fieldAttrEntity.getSubForm().getItems();
                explainSubList.addAll(items);
            }
        });
        explainSubList.forEach(fieldAttrEntity -> {
            if (Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.NAME.getAttr())){
                List<LinkedAttrPoJo> explainLink = fieldAttrEntity.getLinkInfo().getLinkedAttr();
                explainLink.forEach(linkedAttrPoJo -> {
                    FieldAttrEntity fieldAttrEnt = new FieldAttrEntity();
                    if(Objects.equals(linkedAttrPoJo.getAttr(), ProductEnum.NAME.getAttr())
                            || Objects.equals(linkedAttrPoJo.getAttr(), ProductEnum.SERIALNO.getAttr())
                            || Objects.equals(linkedAttrPoJo.getAttr(), ProductEnum.PRODUCT_IMGS.getAttr())
                            || Objects.equals(linkedAttrPoJo.getAttr(), ProductEnum.SPECIFICATION.getAttr())){
                        fieldAttrEnt.setAttr(linkedAttrPoJo.getAttr());
                        fieldAttrEnt.setAttrName(linkedAttrPoJo.getAttrName());
                        fieldAttrEnt.setSaasAttr(linkedAttrPoJo.getSaasAttr());
                        fieldAttrEnt.setEditable(linkedAttrPoJo.getEditable());
                        explainList.add(fieldAttrEnt);
                    }
                });
            }else if (Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.UNIT.getAttr())
                    || Objects.equals(fieldAttrEntity.getAttr(), SelectProductEnum.WAIT_INSTOCK_NUM.getAttr())
                    || Objects.equals(fieldAttrEntity.getAttr(), SelectProductEnum.MEMO.getAttr())){
                explainList.add(fieldAttrEntity);
            }
        });
        for (FieldAttrEntity fieldAttrEntity : explainList){
            if(Objects.equals(fieldAttrEntity.getAttr(),SelectProductEnum.WAIT_INSTOCK_NUM.getAttr())){
                fieldAttrEntity.setAttr(WaitInstockEnum.STOCK.getAttr());
                fieldAttrEntity.setAttrName(WaitInstockEnum.STOCK.getAttrName());
                fieldAttrEntity.setAttrNameEn(WaitInstockEnum.STOCK.getAttrName());
                fieldAttrEntity.setFieldType(WaitInstockEnum.STOCK.getFieldType());
                fieldAttrEntity.setLinkedType(WaitInstockEnum.STOCK.getLinkedType());
                fieldAttrEntity.setEditable(BasicConstant.ZERO);
                fieldAttrEntity.setVisibleScopeEnable(BasicConstant.ZERO);
            }else if(Objects.equals(fieldAttrEntity.getAttr(),SelectProductEnum.MEMO.getAttr())){
                fieldAttrEntity.setAttr(WaitInstockEnum.MEMO.getAttr());
                fieldAttrEntity.setFieldType(WaitInstockEnum.MEMO.getFieldType());
                fieldAttrEntity.setLinkedType(WaitInstockEnum.MEMO.getLinkedType());
                fieldAttrEntity.setEditable(BasicConstant.ZERO);
            }else if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.NAME.getAttr())){
                fieldAttrEntity.setAttr(WaitInstockEnum.PRODUCT_NAME.getAttr());
                fieldAttrEntity.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
                fieldAttrEntity.setLinkedType(WaitInstockEnum.PRODUCT_NAME.getLinkedType());
            }else if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.SERIALNO.getAttr())){
                fieldAttrEntity.setAttr(WaitInstockEnum.PRODUCT_NO.getAttr());
                fieldAttrEntity.setLinkedType(WaitInstockEnum.PRODUCT_NO.getLinkedType());
                fieldAttrEntity.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
            }else if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.SPECIFICATION.getAttr())){
                fieldAttrEntity.setAttr(WaitInstockEnum.SPECIFICATION.getAttr());
                fieldAttrEntity.setLinkedType(WaitInstockEnum.SPECIFICATION.getLinkedType());
                fieldAttrEntity.setFieldType(WaitInstockEnum.SPECIFICATION.getFieldType());
                fieldAttrEntity.setEditable(BasicConstant.ZERO);
                fieldAttrEntity.setDisableListSort(BasicConstant.ONE);
            }else if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.PRODUCT_IMGS.getAttr())){
                fieldAttrEntity.setAttr(WaitInstockEnum.PRODUCT_IMGS.getAttr());
                fieldAttrEntity.setLinkedType(WaitInstockEnum.PRODUCT_IMGS.getLinkedType());
                fieldAttrEntity.setFieldType(WaitInstockEnum.PRODUCT_IMGS.getFieldType());
                fieldAttrEntity.setEditable(BasicConstant.ZERO);
            }
            formDataListDTO.getExplainMap().put(fieldAttrEntity.getAttr(),fieldAttrEntity);
            formDataListVO.getExplainMap().put(fieldAttrEntity.getAttr(),fieldAttrEntity);
        }
        return explainList;
    }

    /**
     * 获得待入库二级筛选条件
     * @param formDataListDTO
     * @param param
     */
    public void getWaitInstockProductFilter(FormDataListDTO formDataListDTO, Map<String, Object> param){
        List<ConditionsEntityExt> conditions = formDataListDTO.getConditions();
        conditions.forEach(conditionsEntityExt -> {
            if (Objects.equals(conditionsEntityExt.getAttr(),"array_1")){
                param.put("productIdIn",conditionsEntityExt.getValue());
            }
            if (Objects.equals(conditionsEntityExt.getAttr(),"array_2")){
                param.put("purchaseIdIn",conditionsEntityExt.getValue());
            }
        });
        UserEntity userEntity = new UserEntity();
        UserVO userVO = formDataListDTO.getLoginUser();
        BeanUtil.copyProperties(userVO, userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity);
        List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, userVO.getUserId(), userVO.getCorpid(), BasicConstant.ZERO,false);
        param.put("userIdIn",userIdIn);
    }

    /**
     * 获得待入库排序条件
     * @param formDataListDTO
     * @param param
     */
    public void getWaitInstockColumn(FormDataListDTO formDataListDTO, Map<String, Object> param){
        Map<String, String> sort = formDataListDTO.getSortMap();
        String field = sort.get("field");
        if (Objects.isNull(field) || Objects.equals(field, "")){
            formDataListDTO.getSortMap().clear();
        }
        formDataListSearchHelp.setListColumn(formDataListDTO);
        if (formDataListDTO.getSortMap().size() !=0){
            Map<String, String> sortMap = formDataListDTO.getSortMap();
            if (WaitInstockEnum.isPurchaseAndProduct(sortMap.get("field"))){
                if (Objects.equals(sortMap.get("field"), WaitInstockEnum.STOCK.getAttr())){
                    param.put("orderByStr","product_num-instock_num " + sortMap.get("sort"));
                }else {
                    String value = WaitInstockEnum.getFeildName(sortMap.get("field"));
                    param.put("orderByStr",value + " " + sortMap.get("sort"));
                }
            }else if (Objects.equals(sortMap.get("field"), "updateTime")){
                param.put("orderByStr","update_time " + sortMap.get("sort"));
            }else if (Objects.equals(sortMap.get("field"), "addTime")){
                param.put("orderByStr","add_time " + sortMap.get("sort"));
            }
            formDataListDTO.getSortMap().clear();
        }else {
            param.put("orderByStr","update_time desc");
        }
        //获得模糊查询条件
        if (Objects.nonNull(formDataListDTO.getNameLike())){
            param.put("nameLike",formDataListDTO.getNameLike());
            formDataListDTO.setNameLike(null);
        }
    }

    /**
     * 待入库产品维度合同参数添加
     */
    public void getWaitInstockPurchaseId(FormDataListDTO formDataListDTO, Map<String, Object> param) throws XbbException {
        try{
            formDataListDTO.getConditions().clear();
            formDataListDTO.getCommonFilter().clear();
            List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
            //合同二级筛选条件
            List purchaseIdList = (List) param.get("purchaseIdIn");
            if(Objects.nonNull(purchaseIdList)){
                ConditionsEntityExt idConditionsEntity = new ConditionsEntityExt();
                idConditionsEntity.setAttr(FieldTypeEnum.ID.getAlias());
                idConditionsEntity.setFieldType(FieldTypeEnum.DATAID.getType());
                idConditionsEntity.setSymbol(ConditionEnum.INCLUDE.getSymbol());
                idConditionsEntity.setValue(purchaseIdList);
                conditionList.add(idConditionsEntity);
            }
            //采购合同未关闭
            ConditionsEntityExt instockconditionsEntity = new ConditionsEntityExt();
            instockconditionsEntity.setAttr(PurchaseEnum.RECEIVE_STATUS.getAttr());
            instockconditionsEntity.setFieldType(PurchaseEnum.RECEIVE_STATUS.getFieldType());
            instockconditionsEntity.setName(PurchaseEnum.RECEIVE_STATUS.getAttrName());
            instockconditionsEntity.setSubAttr("");
            instockconditionsEntity.setSymbol(ConditionEnum.NOEQUAL.getSymbol());
            instockconditionsEntity.setValue(Collections.singletonList(ReceiveStatusEnum.CLOSED.getCode()));
            conditionList.add(instockconditionsEntity);
            //未完全入库
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setAttr(PurchaseEnum.ALL_INCOMING.getAttr());
            conditionsEntityExt.setFieldType(PurchaseEnum.ALL_INCOMING.getFieldType());
            conditionsEntityExt.setName(PurchaseEnum.ALL_INCOMING.getAttrName());
            conditionsEntityExt.setSubAttr("");
            conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            conditionsEntityExt.setValue(Collections.singletonList(0));
            conditionList.add(conditionsEntityExt);
            //审批通过的数据
            ConditionsEntityExt flowStatusConditionsEntityExt = new ConditionsEntityExt();
            flowStatusConditionsEntityExt.setAttr(FieldTypeEnum.FLOW_STATUS.getAlias());
            flowStatusConditionsEntityExt.setFieldType(FieldTypeEnum.FLOW_STATUS.getType());
            flowStatusConditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
            flowStatusConditionsEntityExt.setSubAttr("");
            flowStatusConditionsEntityExt.setValue(Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType()));
            conditionList.add(flowStatusConditionsEntityExt);
            //处理查询条件
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", formDataListDTO.getCorpid()));
            boolQueryBuilder.filter(termQuery("del", 0));
            commonFilter(formDataListDTO);
            EsUtil.parseCondition(boolQueryBuilder,formDataListDTO.getConditions(),formDataListDTO.getRel(),formDataListDTO.getCorpid(),formDataListDTO.getBusinessType());
            //查询数据
            List<Long> dataIdList = new ArrayList<>();
            List<PaasFormDataEntity> paasFormDataEntities = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PURCHASE,boolQueryBuilder,PaasFormDataEntity.class,Arrays.asList(FieldTypeEnum.DATAID.getAlias()),new ArrayList<>());
            paasFormDataEntities.forEach(paasFormDataEntity -> dataIdList.add(paasFormDataEntity.getDataId()));
            param.put("purchaseIdIn",dataIdList);
            formDataListDTO.getConditions().clear();
        }catch (Exception e) {
            Log.error("错误信息", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100071);
        }
    }

    /**
     *处理待入库导出时勾选的参数
     * @param formDataListDTO
     * @param param
     */
    public void getWaitInstockImportParam(FormDataListDTO formDataListDTO, Map<String, Object> param){
        //导出时，处理参数
        Integer fromExport = formDataListDTO.getFromExport();
        List<String> linkIdIn = formDataListDTO.getLinkIdIn();
        boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(fromExport, BasicConstant.ZERO);
        if(notExport && CollectionsUtil.isNotEmpty(linkIdIn)){
            List<Long> linkIdList = new ArrayList<>();
            linkIdIn.forEach(value -> {
                String purchaseIdStr = value.substring(0, value.indexOf("."));
                String productIdStr = value.substring(purchaseIdStr.length()+1, value.length());
                linkIdList.add(Long.valueOf(productIdStr));
            });
            param.put("linkIdIn", linkIdList);
        }
    }

    /**
     * 处理待入库合同二级筛选linkInFo
     * @param explainEnt
     */
    public void waitInstockPurchaseInfo(List<FieldAttrEntity> explainEnt, ExplainScreenListDTO explainScreenListDTO){
        explainEnt.forEach(fieldAttrEntity -> {
            LinkInfoPojo linkInfo = new LinkInfoPojo();
            linkInfo.setLinkAppId(explainScreenListDTO.getAppId());
            linkInfo.setLinkFormId(explainScreenListDTO.getFormId());
            linkInfo.setLinkBusinessType(XbbRefTypeEnum.PURCHASE.getCode());
            linkInfo.setLinkSaasMark(BasicConstant.ONE);
            fieldAttrEntity.setLinkInfo(linkInfo);
        });
    }

    /**
     * 处理待入库合同二级筛选linkInFo
     * @param explainEnt
     */
    public void waitOutContractInfo(List<FieldAttrEntity> explainEnt, ExplainScreenListDTO explainScreenListDTO){
        for (FieldAttrEntity fieldAttrEntity:explainEnt){
            LinkInfoPojo linkInfo = new LinkInfoPojo();
            linkInfo.setLinkAppId(explainScreenListDTO.getAppId());
            linkInfo.setLinkFormId(explainScreenListDTO.getFormId());
            if (Objects.equals(explainScreenListDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                linkInfo.setLinkBusinessType(XbbRefTypeEnum.ORDER.getCode());
            }else {
                linkInfo.setLinkBusinessType(XbbRefTypeEnum.CONTRACT.getCode());
            }
            linkInfo.setLinkSaasMark(BasicConstant.ONE);
            fieldAttrEntity.setLinkInfo(linkInfo);
        }
    }

    public void setOnlyDBData(FormDataListDTO formDataListDTO, PaasFormDataEsListVO formDataListVO) throws XbbException {
        Integer businessType = formDataListDTO.getBusinessType();
        Integer distributorMark = formDataListDTO.getDistributorMark();
        // 枚举获取
        if (!OnlyInsertDBEnum.containBusinessType(businessType, distributorMark)) {
            return;
        }
        List<PaasFormDataEntityExt> list = formDataListVO.getPaasFormDataESList();
        if (CollectionsUtil.isEmpty(list)) {
            return;
        }

        String corpid = formDataListDTO.getCorpid();

        Integer subBusinessType = formDataListDTO.getSubBusinessType();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);


        List<Long> dataIdList = new ArrayList<>();
        list.forEach(item -> dataIdList.add(item.getDataId()));

        // todo 字段解释是否有权限
        List<String> attrList = OnlyInsertDBEnum.getAttrByBusinessType(businessType, distributorMark);
        String dataSql = FormDataUtil.getDataColumns(attrList);
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(StringConstant.IDIN, dataIdList);
        // 查询部分数据
        param.put(StringConstant.COLUMNS, "id, " + dataSql);
        switch (xbbRefTypeEnum) {
            case CONTACT:
                List<ContactEntityExt> contactList = contactModel.findEntitys(param);
                Map<Long, JSONObject> contactMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (ContactEntityExt entityExt : contactList) {
                    contactMap.put(entityExt.getId(), entityExt.getData());
                }
                for (PaasFormDataEntityExt paasFormDataEntityExt : list) {
                    JSONObject data = contactMap.get(paasFormDataEntityExt.getDataId());
                    if (Objects.isNull(data)) {
                        continue;
                    }
                    OnlyInsertDBHelp.setData(businessType, distributorMark, data, paasFormDataEntityExt.getData());
                }
                break;
            default:
                break;
        }
    }

    /**
     * @Author: jiping.yang
     * @Description: 移动端待入库产品维度解释处理
     * @Date: 上午11:06 2022/4/1
     * @Param: []
     * @return: void
     **/
    public void handleWaitInstockExplain(List<FieldAttrEntity> explainList){
        explainList.clear();
        FieldAttrEntity nameAttr = new FieldAttrEntity();
        nameAttr.setAttr(WaitInstockEnum.PRODUCT_NAME.getAttr());
        nameAttr.setAttrName(WaitInstockEnum.PRODUCT_NAME.getAttrName());
        nameAttr.setSaasAttr(WaitInstockEnum.PRODUCT_NAME.getSaasAttr());
        nameAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        nameAttr.setFieldType(FieldTypeEnum.TEXT.getType());
        explainList.add(nameAttr);
        FieldAttrEntity serialNoAttr = new FieldAttrEntity();
        serialNoAttr.setAttr(WaitInstockEnum.PRODUCT_NO.getAttr());
        serialNoAttr.setAttrName(WaitInstockEnum.PRODUCT_NO.getAttrName());
        serialNoAttr.setSaasAttr(WaitInstockEnum.PRODUCT_NO.getSaasAttr());
        serialNoAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        serialNoAttr.setFieldType(FieldTypeEnum.TEXT.getType());
        explainList.add(serialNoAttr);
        FieldAttrEntity unitAttr = new FieldAttrEntity();
        unitAttr.setAttr(WaitInstockEnum.UNIT.getAttr());
        unitAttr.setAttrName(WaitInstockEnum.UNIT.getAttrName());
        unitAttr.setSaasAttr(WaitInstockEnum.UNIT.getSaasAttr());
        unitAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        unitAttr.setFieldType(FieldTypeEnum.TEXT.getType());
        explainList.add(unitAttr);
        FieldAttrEntity updateTimeAttr = new FieldAttrEntity();
        updateTimeAttr.setAttr(WaitInstockEnum.UPDATETIME.getAttr());
        updateTimeAttr.setAttrName(WaitInstockEnum.UPDATETIME.getAttrName());
        updateTimeAttr.setSaasAttr(WaitInstockEnum.UPDATETIME.getSaasAttr());
        updateTimeAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        updateTimeAttr.setFieldType(FieldTypeEnum.UPDATETIME.getType());
        explainList.add(updateTimeAttr);
        FieldAttrEntity addTimeAttr = new FieldAttrEntity();
        addTimeAttr.setAttr(WaitInstockEnum.ADDTIME.getAttr());
        addTimeAttr.setAttrName(WaitInstockEnum.ADDTIME.getAttrName());
        addTimeAttr.setSaasAttr(WaitInstockEnum.ADDTIME.getSaasAttr());
        addTimeAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        addTimeAttr.setFieldType(FieldTypeEnum.ADDTIME.getType());
        explainList.add(addTimeAttr);
    }

    public void handleWaitOutstockExplain(List<FieldAttrEntity> explainList) {
        explainList.clear();
        FieldAttrEntity nameAttr = new FieldAttrEntity();
        nameAttr.setAttr(WaitOutstockEnum.PRODUCT_NAME.getAttr());
        nameAttr.setAttrName(WaitOutstockEnum.PRODUCT_NAME.getAttrName());
        nameAttr.setSaasAttr(WaitOutstockEnum.PRODUCT_NAME.getSaasAttr());
        nameAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        nameAttr.setFieldType(FieldTypeEnum.TEXT.getType());
        explainList.add(nameAttr);
        FieldAttrEntity serialNoAttr = new FieldAttrEntity();
        serialNoAttr.setAttr(WaitOutstockEnum.PRODUCT_NO.getAttr());
        serialNoAttr.setAttrName(WaitOutstockEnum.PRODUCT_NO.getAttrName());
        serialNoAttr.setSaasAttr(WaitOutstockEnum.PRODUCT_NO.getSaasAttr());
        serialNoAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        serialNoAttr.setFieldType(FieldTypeEnum.TEXT.getType());
        explainList.add(serialNoAttr);
        FieldAttrEntity unitAttr = new FieldAttrEntity();
        unitAttr.setAttr(WaitOutstockEnum.UNIT.getAttr());
        unitAttr.setAttrName(WaitOutstockEnum.UNIT.getAttrName());
        unitAttr.setSaasAttr(WaitOutstockEnum.UNIT.getSaasAttr());
        unitAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        unitAttr.setFieldType(FieldTypeEnum.TEXT.getType());
        explainList.add(unitAttr);
        FieldAttrEntity waitOutNumAttr = new FieldAttrEntity();
        waitOutNumAttr.setAttr(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getAttr());
        waitOutNumAttr.setAttrName(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getAttrName());
        waitOutNumAttr.setSaasAttr(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getSaasAttr());
        waitOutNumAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        waitOutNumAttr.setFieldType(FieldTypeEnum.TEXT.getType());
        explainList.add(waitOutNumAttr);
        FieldAttrEntity updateTimeAttr = new FieldAttrEntity();
        updateTimeAttr.setAttr(WaitOutstockEnum.UPDATE_TIME.getAttr());
        updateTimeAttr.setAttrName(WaitOutstockEnum.UPDATE_TIME.getAttrName());
        updateTimeAttr.setSaasAttr(WaitOutstockEnum.UPDATE_TIME.getSaasAttr());
        updateTimeAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        updateTimeAttr.setFieldType(FieldTypeEnum.UPDATETIME.getType());
        explainList.add(updateTimeAttr);
        FieldAttrEntity addTimeAttr = new FieldAttrEntity();
        addTimeAttr.setAttr(WaitOutstockEnum.ADD_TIME.getAttr());
        addTimeAttr.setAttrName(WaitOutstockEnum.ADD_TIME.getAttrName());
        addTimeAttr.setSaasAttr(WaitOutstockEnum.ADD_TIME.getSaasAttr());
        addTimeAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        addTimeAttr.setFieldType(FieldTypeEnum.ADDTIME.getType());
        explainList.add(addTimeAttr);
    }
    public void handleWaitPurchaseExplain(List<FieldAttrEntity> explainList) {
        explainList.clear();
        FieldAttrEntity nameAttr = new FieldAttrEntity();
        nameAttr.setAttr(WaitPurchaseProductEnum.PRODUCT_NAME.getAttr());
        nameAttr.setAttrName(WaitPurchaseProductEnum.PRODUCT_NAME.getAttrName());
        nameAttr.setSaasAttr(WaitPurchaseProductEnum.PRODUCT_NAME.getSaasAttr());
        nameAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        nameAttr.setFieldType(FieldTypeEnum.TEXT.getType());
        explainList.add(nameAttr);
        FieldAttrEntity serialNoAttr = new FieldAttrEntity();
        serialNoAttr.setAttr(WaitPurchaseProductEnum.PRODUCT_NO.getAttr());
        serialNoAttr.setAttrName(WaitPurchaseProductEnum.PRODUCT_NO.getAttrName());
        serialNoAttr.setSaasAttr(WaitPurchaseProductEnum.PRODUCT_NO.getSaasAttr());
        serialNoAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        serialNoAttr.setFieldType(FieldTypeEnum.TEXT.getType());
        explainList.add(serialNoAttr);
        FieldAttrEntity unitAttr = new FieldAttrEntity();
        unitAttr.setAttr(WaitPurchaseProductEnum.UNIT.getAttr());
        unitAttr.setAttrName(WaitPurchaseProductEnum.UNIT.getAttrName());
        unitAttr.setSaasAttr(WaitPurchaseProductEnum.UNIT.getSaasAttr());
        unitAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        unitAttr.setFieldType(FieldTypeEnum.TEXT.getType());
        explainList.add(unitAttr);
        FieldAttrEntity waitOutNumAttr = new FieldAttrEntity();
        waitOutNumAttr.setAttr(WaitPurchaseProductEnum.NUM.getAttr());
        waitOutNumAttr.setAttrName(WaitPurchaseProductEnum.NUM.getAttrName());
        waitOutNumAttr.setSaasAttr(WaitPurchaseProductEnum.NUM.getSaasAttr());
        waitOutNumAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        waitOutNumAttr.setFieldType(FieldTypeEnum.TEXT.getType());
        explainList.add(waitOutNumAttr);
        FieldAttrEntity updateTimeAttr = new FieldAttrEntity();
        updateTimeAttr.setAttr(WaitPurchaseProductEnum.UPDATE_TIME.getAttr());
        updateTimeAttr.setAttrName(WaitPurchaseProductEnum.UPDATE_TIME.getAttrName());
        updateTimeAttr.setSaasAttr(WaitPurchaseProductEnum.UPDATE_TIME.getSaasAttr());
        updateTimeAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        updateTimeAttr.setFieldType(FieldTypeEnum.UPDATETIME.getType());
        explainList.add(updateTimeAttr);
        FieldAttrEntity addTimeAttr = new FieldAttrEntity();
        addTimeAttr.setAttr(WaitPurchaseProductEnum.ADD_TIME.getAttr());
        addTimeAttr.setAttrName(WaitPurchaseProductEnum.ADD_TIME.getAttrName());
        addTimeAttr.setSaasAttr(WaitPurchaseProductEnum.ADD_TIME.getSaasAttr());
        addTimeAttr.setLinkedType(XbbRefTypeEnum.PRODUCT.getCode());
        addTimeAttr.setFieldType(FieldTypeEnum.ADDTIME.getType());
        explainList.add(addTimeAttr);
    }
}
